我有一个相当复杂的linq分组,有些重复让我烦恼,但我无法减少它.有没有办法避免两次获得ID =="XYZ"的项目列表?
var example = = new GdsObservableCollection( 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
...
我不会说更有效,但可以稍微小了一点,因为你可以使用内部谓词Any
和First
:
var example = new GdsObservableCollection( 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
x.Id == "XYZ"
使用Where
+ Select
+ FirstOrDefault
链结合C#null-coalescing运算符可以避免重复搜索:
SectionHeader = g .Where(x => x.Id == "XYZ") .Select(x => "Category :" + x.NewValue) .FirstOrDefault() ?? "Item - " + itemNumber