-4

配列の 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 } };

リスト1の各要素について、リスト2のすべての要素について、それらが持つ共通要素の数を計算することを知りたいです。

元。1,2,3,4 を 1,2 と比較すると、一致する要素が 2 つになります。1,2,3,4 を 3,5 と比較すると、一致する要素が 1 つになります。

通常のリストを比較したくないので、これは重複していません。list1 の各レコードについて、list2 の項目数に共通項目がいくつ含まれているかを確認したいと考えています。

4

5 に答える 5

1
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 ] ]

于 2013-07-11T06:22:11.013 に答える
1

Enumerable.Intersectを使用して、2 番目のリストで最初に見つかった共通項目を見つけることができます。

var commonList = list1.Intersect(list2);

2 つの集合 A と B の交差は、B にも現れる A のすべての要素を含み、他の要素を含まない集合として定義されます。

編集リストの要素として配列があるため、各リスト項目を通過する必要があります。

 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()); 
 }
于 2013-07-11T06:09:23.223 に答える
0
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]
于 2013-07-11T06:12:12.710 に答える
0

次のようにします。

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.
于 2013-07-11T06:10:37.533 に答える