如何在可列举的词典中按键过滤?

时间:2014-08-13 11:05:00

标签: c# dictionary ienumerable

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

enter image description here

我尝试使用此代码来过滤数据,但它仍会返回相同的内容。

  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);

我的最终数据类型为List<Dictionary<string, object>>

1 个答案:

答案 0 :(得分:1)

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

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());