这个LINQ可以更高效吗?

时间:2017-01-25 18:13:00

标签: c# performance linq

我有一个相当复杂的linq分组,有些重复让我烦恼,但我还没有能够减少它。有没有办法避免获得ID ==" XYZ"的项目列表?两次?

var example = = new GdsObservableCollection<GroupedQueryResults>(
                items.Where(a => a.SubCategory3 != "{template}")
                     .GroupBy(item => item.SubCategory1)
                     .Select(g => new GroupedQueryResults
                                  {
                                     SubCategory = g.Key,
                                     SectionHeader = (g.Count(x => x.Id == "XYZ") > 0) ?
                                     "Category :" +  g.Where(x => x.Id == "XYZ")
                                                     .First().NewValue :
                                     "Item - " + itemNumber

...

2 个答案:

答案 0 :(得分:5)

我不会说效率更高,但可以更小一些,因为您可以在AnyFirst中使用谓词:

var example = new GdsObservableCollection<GroupedQueryResults>(
            items.Where(a => a.SubCategory3 != "{template}")
                 .GroupBy(item => item.SubCategory1)
                 .Select(g => new GroupedQueryResults
                              {
                                 SubCategory = g.Key,
                                 SectionHeader = g.Any(x => x.Id == "XYZ") ?
                                 "Category :" +  g.First(x => x.Id == "XYZ").NewValue :
                                 "Item - " + itemNumber

答案 1 :(得分:5)

使用x.Id == "XYZ" + Where + Select链与C#null-coalescing运算符相结合,可以避免重复搜索FirstOrDefault

SectionHeader = g
    .Where(x => x.Id == "XYZ")
    .Select(x => "Category :" +  x.NewValue)
    .FirstOrDefault() ?? "Item - " + itemNumber