C# 有条件地分组列表项

C# 有条件地分组列表项,c#,linq,list,group-by,conditional,C#,Linq,List,Group By,Conditional,在下面的代码中,我基于一个特定属性创建了两个列表,该属性决定了我分组的依据。然后,我将两个列表连接成一个列表 var naFundCodeGroups = (from sar in aidItems where sar.SuFundCode.Substring(0, 2) != "SA" gr

在下面的代码中,我基于一个特定属性创建了两个列表,该属性决定了我分组的依据。然后,我将两个列表连接成一个列表

    var naFundCodeGroups = (from sar in aidItems      
                            where sar.SuFundCode.Substring(0, 2) != "SA"                                     
                            group sar by sar.NaFundCode into sa
                            select sa).ToList();

    var suFundCodeGroups = (from sar in aidItems
                            where sar.SuFundCode.Substring(0, 2) == "SA"
                            group sar by sar.SuFundCode
                            into sa
                            select sa).ToList();

    var fundCodeGroups = naFundCodeGroups.Concat(suFundCodeGroups).ToList();
有更优雅的方法吗?
例如,在单个语句中以某种方式通过条件生成组


感谢您在这方面提供的帮助。

如果SuFundCode和NaFundCode集合之间没有公共值,那么请坚持使用查询理解语法,这样应该可以:

var fundCodeGroups = (from sar in aidItems
   group sar by (sar.SuFundCode.Substring(0, 2) == "SA" ?
      sar.SuFundCode : sar.NaFundCode)
   into sa
   select sa).ToList();
或者使用更紧凑(在本例中更可读)的fluent/lambda语法:

var fundCodeGroups = aidItems
   .GroupBy(sar => sar.SuFundCode.Substring(0, 2) == "SA" ?
      sar.SuFundCode : sar.NaFundCode)
   .ToList();
否则,其中任何一项都应该有效,尽管只有最后一项返回的分组类型与原始分组类型相同:

var fundCodeGroups1 = (from sar in aidItems
   group sar by new { IsSA = sar.SuFundCode.Substring(0, 2) == "SA",
      Code = (sar.SuFundCode.Substring(0, 2) == "SA" ? sar.SuFundCode : sar.NaFundCode) }
   into sa
   select sa).ToList();

var fundCodeGroups2 = aidItems
   .GroupBy(sar => new { IsSA = sar.SuFundCode.Substring(0, 2) == "SA",
      Code = (sar.SuFundCode.Substring(0, 2) == "SA" ? sar.SuFundCode : sar.NaFundCode) })
   .ToList();

var fundCodeGroups3 = aidItems
   .GroupBy(sar => sar.SuFundCode.Substring(0, 2) == "SA")
   .SelectMany(g => g.Key ? g.GroupBy(i => i.SuFundCode) : g.GroupBy(i => i.NaFundCode))
   .ToList();

不过,我不确定这些解决方案是否比您原来的解决方案更清晰或性能更好。

我认为您不可能在一句话中实现同样的效果