【发布时间】:2010-12-27 20:42:56
【问题描述】:
我正在重构这段代码,并试图想出一个简单的 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 的情况下内联完成所有操作?提前致谢。
【问题讨论】:
标签: c# .net linq collections