帮助Linqifying集合到字典

Jac*_*hea 6 .net c# linq collections

我正在重构这段代码,并试图想出一个简单的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我只能实现一个自定义IEqualityComparer,并在诸如此类的表达式中使用它...

headers.Distinct(new CustomComparer()).ToDictionary();
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在没有自定义IEqualityComparer的情况下全部内联?提前致谢.

Mar*_*ell 13

    var qry = headers.GroupBy(row => row.DestinationLocation)
        .ToDictionary(grp => grp.Key, grp => grp.First());
Run Code Online (Sandbox Code Playgroud)

或同等学历):

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

不过,我想知道,如果你当前的foreach代码还没有更好 - 例如,它不会缓冲它想要删除的代码.


Gre*_*ech 5

我前段时间写了一篇博文,向您展示了如何使用lambda表达式作为键选择器而不是自定义比较器来创建Distinct的重载,这可以让您编写:

headers.Distinct(h => h.DestinationLocation)
       .ToDictionary(h => h.DestinationLocation);
Run Code Online (Sandbox Code Playgroud)

它确实使用了下面的自定义比较器,但扩展方法为您构造了这些东西,并使其更容易阅读.

  • 那它很赏心悦目。 (2认同)