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