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

1830
2024/3/3 10:12:00
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要求两个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中的交集数据,并输出结果。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#递归算法有哪些特点