C#如何求两个List字典类型数据的交集
导读:要求两个List中字典类型数据的交集,可以使用LINQ查询语句和Intersect方法来实现。以下是一个示例代码: using System; using System.Collections.Generic; using System.L...
要求两个List中字典类型数据的交集,可以使用LINQ查询语句和Intersect方法来实现。以下是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
ListDictionarystring, string>
>
list1 = new ListDictionarystring, string>
>
{
new Dictionarystring, string>
{
{
"key1", "value1" }
, {
"key2", "value2" }
}
,
new Dictionarystring, string>
{
{
"key3", "value3" }
, {
"key4", "value4" }
}
}
;
ListDictionarystring, string>
>
list2 = new ListDictionarystring, string>
>
{
new Dictionarystring, string>
{
{
"key1", "value1" }
, {
"key2", "value2" }
}
,
new Dictionarystring, 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 : IEqualityComparerDictionarystring, string>
>
{
public bool Equals(Dictionarystring, string>
x, Dictionarystring, 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(Dictionarystring, 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中的交集数据,并输出结果。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C#如何求两个List字典类型数据的交集
本文地址: https://pptw.com/jishu/667724.html
