如何比较列表中的数组

时间:2013-12-27 14:31:13

标签: c# arrays list compare

我有一个List包含各种大小的数组。例如:

enter image description here

  • 0和7. arrrays具有相同的数据{1,2,3,4,5,6}

  • 2,4和5.数组具有相同的数据{1,2,3}

  • 注意! 3和6没有相同的数据[3] = {1,2} , [6] = {1,3}

我想获取哪些索引具有相同的数据,并将此索引添加到另一个List。例如

anotherList[ 0 ] = {0,7}

anotherList[ 1 ] = {2,4,5}

我该怎么做?

提前致谢。

3 个答案:

答案 0 :(得分:1)

你可以使用这段代码(Linq ie SequenceEqual 在这里非常有用):

    private static IList<IList<int>> EqualArrays(List<int[]> list) {
      IList<IList<int>> result = new List<IList<int>>();

      HashSet<int> proceeded = new HashSet<int>();

      for (int i = 0; i < list.Count; ++i) {
        if (proceeded.Contains(i))
          continue;

        int[] item = list[i];
        List<int> equals = new List<int>() { i };

        result.Add(equals);

        for (int j = i + 1; j < list.Count; ++j)
          if (item.SequenceEqual(list[j])) {
            equals.Add(j);
            proceeded.Add(j);
          }
      }

      return result;
    }


   ...

   // Your test case:
   List<int[]> list = new List<int[]>() {
     new int[] {1, 2, 3, 4, 5, 5, 7},
     new int[] {1},
     new int[] {1, 2, 3},
     new int[] {1, 2},
     new int[] {1, 2, 3},
     new int[] {1, 2, 3},
     new int[] {1, 3},
     new int[] {1, 2, 3, 4, 5, 5, 7}
   };

   // anotherList == {{0, 7}, {1}, {2, 4, 5}, {3}, {6}}
   IList<IList<int>> anotherList = EqualArrays(list);

答案 1 :(得分:0)

试试这个

List<byte[]> anotherList = new List<byte[]>();
foreach (byte[] array in list2)
    if (!list1.Any(a => a.SequenceEqual(array)))
        anotherList.Add(array);

答案 2 :(得分:0)

int[][] original =
{
    new [] {1,2,3,4,5,6},
    new [] {1},
    new [] {1,2,3},
    new [] {1,2},
    new [] {1,2,3},
    new [] {1,2,3},
    new [] {1,3},
    new [] {1,2,3,4,5,6},
};

int[][] anotherList =
    original.Select((values, index) => new { values, index })
            .GroupBy(x => x.values, SequenceComparer<int>.Default)
            .Where(grouping => grouping.Count() > 1)   // optional
            .Select(grouping => grouping.Select(x => x.index).ToArray())
            .ToArray();

我已经从here(和here)调整了SequenceComparer<T>的定义:

public class SequenceComparer<T> : IEqualityComparer<IEnumerable<T>>
{
    public static readonly SequenceComparer<T> Default = new SequenceComparer<T>();

    public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
    {
        if (Object.ReferenceEquals(x, y))
            return true;

        return x != null && y != null && x.SequenceEqual(y);
    }

    public int GetHashCode(IEnumerable<T> seq)
    {
        if (seq == null)
            return 0;

        unchecked
        {
            const int p = 16777619;
            const int hash = (int)2166136261;

            return seq.Select(e => e.GetHashCode())
                      .Aggregate(hash, (a, b) => (a ^ b) * p));
        }
    }
}