【问题标题】:Help Linqifying collection to Dictionary帮助 Linqifying 集合到字典
【发布时间】: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


    【解决方案1】:

    我不久前写了一个blog post,向您展示了如何创建使用 lambda 表达式作为键选择器而不是自定义比较器的 Distinct 重载,这样您就可以编写:

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

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

    【讨论】:

    • 那它非常赏心悦目。
    【解决方案2】:
    var headerLocationLookup = PopulateHeaders()
        .Aggregate(new Dictionary<string, IHeaderRecord>(), (header, d) => {
            if(d.ContainsKey(header.DestinationLocation)) 
                d[header.DestinationLocation] = header;
    
            return d;
        });
    

    我认为这并不比现有代码更清晰。

    【讨论】:

      【解决方案3】:
          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 代码还不够好 - 例如,它不会缓冲它打算删除的代码。

      【讨论】:

      • 好答案。我认为你是对的,当前的代码更清晰。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多