2014-02-07 63 views
0

在下面的代码中,我创建了两个基于特定属性的列表,这些列表决定了我通过分组的内容。然后我将两个列表连接成一个列表。有条件的分组列表项目

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(); 

有没有更好的方法来做到这一点?
例如,通过条件在某个语句中以某种方式进行组合。

感谢您的任何帮助。

+0

我不认为你可以在一个声明中实现同一件事 –

回答

1

如果有套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(); 

或者用更紧凑的(在这种情况下更具有可读性,国际海事组织)流利/ 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(); 

尽管如此,我不确定这些中的任何一个都能提供比原始解决方案更好的清晰度或性能。