Linq比较两个数组列表
本文关键字:两个 数组 列表 比较 Linq | 更新日期: 2023-09-27 18:21:51
我想比较两个数组列表。举个例子:
List<int[]> list1 = new List<int[]>() { new int[4] { 1, 2, 3, 4 }, new int[4] { 1, 2, 3, 5 } };
List<int[]> list2 = new List<int[]>() { new int[2] { 1, 2 }, new int[2] { 3, 4 }, new int[2] { 3, 5 } };
我想知道列表1中的每个元素计算列表2中的每个元素有多少公共元素。
Ex。1,2,3,4与1,2相比将产生2个匹配元素。1,2,3,4与3,5相比将产生1个匹配元素。
这是不重复的,因为我不想比较常规列表。我想看看列表1中的每条记录,列表2中有多少项目包含多少常见项目。
List<int[]> list1 = new List<int[]>() { new int[4] { 1, 2, 3, 4 }, new int[4] { 1, 2, 3, 5 } };
List<int[]> list2 = new List<int[]>() { new int[2] { 1, 2 }, new int[2] { 3, 4 }, new int[2] { 3, 5 } };
var results = list1.Select(x => list2.Select(y => y.Intersect(x).Count()).ToList()).ToList();
结果包含以下数据:[ [ 2, 2, 1 ], [ 2, 1, 2 ] ]
您可以使用Enumerable.Intersect来查找第二个列表中第一个列表的常见项。
var commonList = list1.Intersect(list2);
两个集合A和B的交集被定义为包含A的所有元素,这些元素也出现在B中,但没有其他元素元件
编辑由于您将数组作为列表元素,因此必须遍历每个列表项。
List<int[]> list1 = new List<int[]>() { new int[4] { 1, 2, 3, 4 }, new int[4] { 1, 2, 3, 5 } };
List<int[]> list2 = new List<int[]>() { new int[2] { 1, 2 }, new int[2] { 3, 4 }, new int[2] { 3, 5 } };
List<int[]> list3 = new List<int[]>();
for (int i = 0; i < list1.Count; i++)
{
list3.Add(list1[i].Intersect(list2[i]).ToArray());
}
您可以这样做:
var results =
from x in list1.Select((array, index) => new { array, index })
from y in list2.Select((array, index) => new { array, index })
select new
{
list1_index = x.index,
list2_index = y.index,
count = x.array.Intersect(y.array).Count()
};
foreach(var r in results)
{
Console.WriteLine("({0}, {1}) have {2} item(s) in common.", r.list1_index, r.list2_index, r.count);
}
// (0, 0) have 2 item(s) in common.
// (0, 1) have 2 item(s) in common.
// (0, 2) have 1 item(s) in common.
// (1, 0) have 2 item(s) in common.
// (1, 1) have 1 item(s) in common.
// (1, 2) have 2 item(s) in common.
var commons = list1.Select(x => list2.Select(x.Intersect).ToArray()).ToArray();
Console.WriteLine(commons[0][0]); // Commons between list1[0] and list2[0]
Console.WriteLine(commons[0][1]); // Commons between list1[0] and list2[1]
Console.WriteLine(commons[3][0]); // Commons between list1[3] and list2[0]
Console.WriteLine(commons[3][0].Length); // Number of commons between [3] and [0]
根据您的要求,我认为在C#中,列表中没有这样的内置函数可以完全按照您的要求执行,但下面的函数可以完全返回resultList中所需的内容。希望这对你有所帮助。
private List<int> MatchList()
{
List<int[]> list1 = new List<int[]>() { new int[4] { 1, 2, 3, 4 }, new int[4] { 1, 2, 3, 5 } };
List<int[]> list2 = new List<int[]>() { new int[2] { 1, 2 }, new int[2] { 3, 4 }, new int[2] { 3, 5 } };
List<int> resultList = new List<int>();
for (int i = 0; i < list1.Count; i++)
{
for (int j = 0; j < list2.Count; j++)
{
if (i == j)
{
int result = 0;
foreach (int list1Element in list1[i])
{
foreach (int list2Element in list2[j])
{
if (list1Element == list2Element)
{
result +=1;
}
}
}
resultList.Add(result);
}
}
}
return resultList;
}