簡體   English   中英

幫助Linqifying集合到字典

[英]Help Linqifying collection to Dictionary

我正在重構這段代碼,並試圖想出一個簡單的linq表達式來填充這個詞典。

IEnumerable<IHeaderRecord> headers = PopulateHeaders();
var headerLocationLookup = new Dictionary<string, IHeaderRecord>();

foreach (var header in headers)
{
//destination locations can repeat, if they do, dictionary should only contain the first header associated with a particular location
    if (!headerLocationLookup.ContainsKey(header.DestinationLocation)) 
    {
         headerLocationLookup[header.DestinationLocation] = header;
    }
}

我只能實現一個自定義的IEqualityComparer,並在諸如此類的表達式中使用它...

headers.Distinct(new CustomComparer()).ToDictionary();

有沒有一種方法可以在沒有自定義IEqualityComparer的情況下全部內聯? 提前致謝。

    var qry = headers.GroupBy(row => row.DestinationLocation)
        .ToDictionary(grp => grp.Key, grp => grp.First());

或同等學歷):

    var dictionary = (from row  in headers
              group row by row.DestinationLocation)
              .ToDictionary(grp => grp.Key, grp => grp.First());

不過,我想知道,如果你當前的foreach代碼還沒有更好 - 例如,它不會緩沖它想要刪除的代碼。

我前段時間寫了一篇博文 ,向您展示了如何使用lambda表達式作為鍵選擇器而不是自定義比較器來創建Distinct的重載,這可以讓您編寫:

headers.Distinct(h => h.DestinationLocation)
       .ToDictionary(h => h.DestinationLocation);

它確實使用了下面的自定義比較器,但擴展方法為您構造了這些東西,並使其更容易閱讀。

var headerLocationLookup = PopulateHeaders()
    .Aggregate(new Dictionary<string, IHeaderRecord>(), (header, d) => {
        if(d.ContainsKey(header.DestinationLocation)) 
            d[header.DestinationLocation] = header;

        return d;
    });

我不認為這比現有代碼更清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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