【问题标题】:How to filter by key in an enumerable of dictionaries?如何在可枚举的字典中按键过滤?
【发布时间】:2014-08-13 11:05:00
【问题描述】:

我有一个可枚举的字典集合,其中包含一些重复值。我想删除那些重复的值,这是我的数据,其中 ID 重复但具有不同的 CompanyID

我尝试了这段代码来过滤数据,但它仍然返回相同的结果。

  foreach (int rowval in rowscol)
                    {    
                        Dictionary<string, object> Data = new Dictionary<string, object>();
                        foreach (Contracts.CommonDataField field in finalColumns)
                        {
                            string value = record.CommonDataValues.SingleOrDefault(row => row.RowID == rowval && row.FieldName == field.FieldName).RecordFieldData.ToString();
                            Data.Add(field.FieldName, value);
                        }
                       finaldata.Add(Data);
                     }
 var dresult = finaldata.GroupBy(x => x.Keys).Select(g => g.First()).ToDictionary(x => x.Values);

我的 finaldata 类型是 List&lt;Dictionary&lt;string, object&gt;&gt;

【问题讨论】:

标签: c# dictionary ienumerable


【解决方案1】:

您可以使用Enumerable.Distinct Method (IEnumerable, IEqualityComparer)
例如,如果你想检查“ID”键,你可以使用这样的东西

public class DictionaryEqualityComparer : IEqualityComparer<Dictionary<string,object>>
{

    public bool Equals(Dictionary<string, object> x, Dictionary<string, object> y)
    {
        object xid,yid;
        return x.TryGetValue("ID", out xid) 
            && y.TryGetValue("ID", out yid)
            && ((int)xid == (int)yid); //note: `int` only for example, use your type for "ID" key
    }

    public int GetHashCode(Dictionary<string, object> obj)
    {
        object xid;
        return obj.TryGetValue("ID", out xid) ? xid.GetHashCode() : obj.GetHashCode();
    }
}

并像使用它一样

var dresult = finaldata.Distinct(new DictionaryEqualityComparer());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多