我有一个相当复杂的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
...
答案 0 :(得分:5)
我不会说效率更高,但可以更小一些,因为您可以在Any
和First
中使用谓词:
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