[英]Can this LINQ be more efficient?
我有一個相當復雜的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
...
我不會說效率更高,但可以更小一點,因為你可以在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
通過使用Where
+ Select
+ FirstOrDefault
鏈與C#null-coalescing運算符結合,可以避免重復搜索x.Id == "XYZ"
:
SectionHeader = g
.Where(x => x.Id == "XYZ")
.Select(x => "Category :" + x.NewValue)
.FirstOrDefault() ?? "Item - " + itemNumber
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.