在linqPad中使用了SelectMany结果报错无法从用法推断。尝试显式指定类型参数。
原因就是类型不匹配,SelectMany需要的是一个List,list.SelectMany(p=>p)会出错,因为p是一条数据 ,将数组中带有数组的数据进行拼凑聚合。
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)
比如数据是这样的情况
这里用一下这位老哥的数据https://blog.csdn.net/xuchen_wang/article/details/91824945 机械键盘侠 2019-06-13 15:36:52
public class Person
{
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public List<Phone> Phones { get; set; }
}
public class Phone
{
public string Country { get; set; }
public string City { get; set; }
public string Name { get; set; }
}
void Main()
{
List<Person> PersonLists = new List<Person>()
{
new Person { Name = "张三",Age = 20,Gender = "男",
Phones = new List<Phone> {
new Phone { Country = "中国", City = "北京", Name = "小米" },
new Phone { Country = "中国",City = "北京",Name = "华为"},
new Phone { Country = "中国",City = "北京",Name = "联想"},
new Phone { Country = "中国",City = "台北",Name = "魅族"},
}
},
new Person { Name = "松下",Age = 30,Gender = "男",
Phones = new List<Phone> {
new Phone { Country = "日本",City = "东京",Name = "索尼"},
new Phone { Country = "日本",City = "大阪",Name = "夏普"},
new Phone { Country = "日本",City = "东京",Name = "松下"},
}
},
new Person { Name = "克里斯",Age = 40,Gender = "男",
Phones = new List<Phone> {
new Phone { Country = "美国",City = "加州",Name = "苹果"},
new Phone { Country = "美国",City = "华盛顿",Name = "三星"},
new Phone { Country = "美国",City = "华盛顿",Name = "HTC"}
}
}
};
var Lists = PersonLists.SelectMany(p => p).Dump();//此方法的第一个重载
var selectsList = PersonLists.Select(p => p.Phones).Dump();
}
这时就会报错
无法从用法推断。尝试显式指定类型参数。然而是因为参数的类型不对,来到官网看函数定义
SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)
发现要 IEnumerable<TSource> 类型 PersonLists.SelectMany(p => p) 中的p是personlists中的一项所以类型不匹配
var Lists = PersonLists.SelectMany(p => p.Phones).Dump();
var selectsList = PersonLists.Select(p => p.Phones).Dump();
p.Phones 就是个 list 了这时就会聚合list
selectMany
select
在开发中我们可以把复杂的select转化成selectMany来降低开发难度。