要求兩個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中的交集數據,并輸出結果。