簡體   English   中英

這個LINQ可以更高效嗎?

[英]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

...

我不會說效率更高,但可以更小一點,因為你可以在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

通過使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM