LINQ SelectMany cannot be inferred from the usage. Try specifying the type arguments explicitly.

在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来降低开发难度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值