List<Dictionary<string, string>> 去重方法

List<Dictionary<string, string>>可以使用LINQ的Distinct()方法来去重。

不过需要提供一个自定义的Comparer。实现接口IEqualityComparer

public class DictionaryComparer : IEqualityComparer<Dictionary<string, string>>
{
    public bool Equals(Dictionary<string, string> x, Dictionary<string, string> y)
    {
        return x.OrderBy(kv => kv.Key).SequenceEqual(y.OrderBy(kv => kv.Key));
    }

    public int GetHashCode(Dictionary<string, string> obj)
    {
        int hash = 0;
        foreach (var pair in obj.OrderBy(kv => kv.Key))
        {
            hash ^= pair.Key.GetHashCode();
            hash ^= pair.Value.GetHashCode();
        }
        return hash;
    }
}

使用方式:

List<Dictionary<string, string>> kvs = new List<Dictionary<string, string>>();
/*给kvs 赋值*/
....
/*distinctList为去重后的List*/
var distinctList = kvs.Distinct(new DictionaryComparer()).ToList();

 

posted @ 2023-08-23 17:47  新*  阅读(94)  评论(0编辑  收藏  举报