【问题标题】:How to avoid duplicates in LINQ for an anonymous type?如何避免 LINQ 中匿名类型的重复?
【发布时间】:2016-02-25 06:27:30
【问题描述】:

我正在尝试将DataTable 转换为字符串和整数字典。 DataTable 有重复,我写了以下代码:

Dictionary<string, short> data = dt.AsEnumerable()
                                   .Select(item => new {
                                                          Key = item.Field<string>("product_name"),
                                                          Value = item.Field<short>("type_id")
                                                        })
                                    .Distinct()
                                    .ToDictionary(dr => dr.Key, dr => dr.Value, StringComparer.OrdinalIgnoreCase);

当我有这样的数据时:

Product1   1
Product1   2
Product2   3
Product4   3

结果应该是这样的:

Product1   1
Product2   3
Product4   3

我的代码出错,因为 Distinct() 考虑了匿名类型中的所有可用属性。有没有办法实现这个 linq 或覆盖 Distinct() 的默认行为?

【问题讨论】:

  • 在确定它是否不同时涉及多少属性?它只是关键吗?
  • 是的,只是关键。我需要获取所有具有相应 type_id 的不同 product_name(这可以是第一次出现的键)。

标签: c# linq


【解决方案1】:

试试这个(通过 Key 区分):

Dictionary<string, short> data = dt.AsEnumerable()
                                       .Select(item => new {
                                                              Key = item.Field<string>("product_name"),
                                                              Value = item.Field<short>("type_id")
                                                            })
                                        .GroupBy(x=>x.Key)
                                        .Select(x=>x.First())
                                        .ToDictionary(dr => dr.Key, dr => dr.Value, StringComparer.OrdinalIgnoreCase);

【讨论】:

  • 是的。这也是我要建议的。
【解决方案2】:

您可以根据文档向Distinct() 提供 IEqualityComparer 的实现:https://msdn.microsoft.com/library/bb338049(v=vs.100).aspx

您可以为您的匿名类型创建这样一个相等比较器,如此堆栈溢出答案中所述:https://stackoverflow.com/a/1071637/1675729

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多