我有一个可枚举的字典集合,其中包含一些重复的值。我想删除那些重复的值,这里是我的数据,其中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);
我的最终数据类型为List<Dictionary<string, object>>
答案 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());