c# list

C#如何求两个List字典类型数据的交集

小亿
111
2024-04-02 10:12:00
栏目: 编程语言

要求两个List中字典类型数据的交集,可以使用LINQ查询语句和Intersect方法来实现。以下是一个示例代码:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Dictionary<string, string>> list1 = new List<Dictionary<string, string>>
        {
            new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } },
            new Dictionary<string, string> { { "key3", "value3" }, { "key4", "value4" } }
        };

        List<Dictionary<string, string>> list2 = new List<Dictionary<string, string>>
        {
            new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } },
            new Dictionary<string, string> { { "key5", "value5" }, { "key6", "value6" } }
        };

        var intersected = list1.Intersect(list2, new DictionaryComparer());

        foreach (var item in intersected)
        {
            foreach (var pair in item)
            {
                Console.WriteLine($"{pair.Key}: {pair.Value}");
            }
        }
    }

    class DictionaryComparer : IEqualityComparer<Dictionary<string, string>>
    {
        public bool Equals(Dictionary<string, string> x, Dictionary<string, string> y)
        {
            if (x.Count != y.Count)
                return false;

            foreach (var pair in x)
            {
                if (!y.ContainsKey(pair.Key) || y[pair.Key] != pair.Value)
                    return false;
            }

            return true;
        }

        public int GetHashCode(Dictionary<string, string> obj)
        {
            int hash = 17;
            foreach (var pair in obj)
            {
                hash = hash * 23 + pair.Key.GetHashCode() + pair.Value.GetHashCode();
            }
            return hash;
        }
    }
}

在上面的示例中,我们定义了一个DictionaryComparer类来实现IEqualityComparer接口,用于比较两个字典类型数据是否相等。然后我们使用Intersect方法来获取两个List中的交集数据,并输出结果。

1
看了该问题的人还看了