【发布时间】:2020-04-21 08:34:34
【问题描述】:
我有一个带有groupBy 参数的查询取决于用户输入。如果条件为真,查询将与DOB 属性分组。否则,它不需要。
这是我的代码
var userList = user.GroupBy(x => new { x.Name, x.Age});
if (isBaby)
{
userList = user.GroupBy(x => new { x.Name, x.Age, x.DOB });
}
但是我得到一个参数不一样的错误。后面的代码就是这样从这个查询中选择的。
var allList= userList.Select({
...
}).ToList();
我不想创建两个select 列表,因为如果只使用一个select 列表更容易管理。
编辑: 这是错误
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<SystemLinq.IGrouping<<anonymous type: string name, string age>, Domains.User>>' to 'System.Collections.Generic.IEnumerable<SystemLinq.IGrouping<<anonymous type: string name, string age, string DOB>, Domains.User>>'
在此处输入代码
【问题讨论】:
-
能否请您附上错误信息?
-
关于错误,你为什么不这样做:` if (isBaby){ var userList = user.GroupBy(x => new { x.Name, x.Age, x.DOB } );} else{ var userList = user.GroupBy(x => new { x.Name, x.Age});}`
-
@fyrz 您正在尝试对已经分组的列表进行分组` if (isBaby) { userList = user.GroupBy(x => new { x.Name, x.Age, x.DOB }); } else { user.GroupBy(x => new { x.Name, x.Age}); }`
-
但是我不能在 if else 语句之外使用 var userList
标签: c# list linq model-view-controller group-by