2

我正在寻找一种从锯齿状数组中获取不同值的方法。我试过把它放在字典里,但它似乎并没有看到这些值是不同的。任何人对解决方案有任何想法吗?这是我到目前为止所拥有的:

int[][] connectionList = GetArray();

从此返回的示例数据:

[0][1, 130, 136, 138]
[1][1, 78, 126, 138]
[2][1, 10, 125, 138]
[3][1, 130, 136, 138]
[4][1, 78, 126, 138]
[5][1, 130, 136, 138]
[6][1, 72, 135, 138]
[7][1, 73, 135, 138]
[8][1, 130, 136, 138]

已尝试添加到字典。我试图在添加重复值时捕获它们,但这没有用,所以尝试添加 .Distinct(),但那里也没有乐趣

Dictionary<int, int[]> myDictionary = new Dictionary<int, int[]>();
for (int i = 0; i < connectionList.Length; i++)
{ 
    List<int> list = new List<int>();
    for (int j = 0; j < connectionList[i].Length; j++)
    {
        list.Add(connectionList[i][j]);        
    }
    if (myDictionary.Where(x => x.Value == list.ToArray()).Count() == 0)
        myDictionary.Add(i, list.ToArray());
}
var distinctList = myDictionary.Values.Distinct().ToList();

从上面的列表中,我正在寻找的输出是:

[0][1, 130, 136, 138]
[1][1, 78, 126, 138]
[2][1, 10, 125, 138]
[4][1, 72, 135, 138]
[5][1, 73, 135, 138]

有什么想法我怎么能做到这一点?

4

3 回答 3

4

这是一种方法:

var distinctList = connectionList.GroupBy(x => string.Join(",", x))
                                 .Select(g => g.First())
                                 .ToList();

尽管创建自定义可能更可取IEqualityComparer<T>——正如Crab BucketTobias所建议的那样——而不是创建用于比较的一次性字符串。

于 2012-01-30T16:13:33.067 回答
2

使用 LINQ 这将很容易Distinct,您只需要提供自己的实现即可IEqualityComparer

public class IntArrayComparer : IEqualityComparer<int[]>
{
    public bool Equals(int[] i1, int[] i2)
    {
        if(ReferenceEquals(i1, i2))
        {
            return true;
        }
        else if(i1 == null || i2 == null)
        {
            return false;
        }
        else if(i1.Length != i2.Length)
        {
            return false;
        }

        for(int i = 0; i < i1.Length; ++i)
        {
            if(i1[i] != i2[i]) return false;
        }

        return true;
    }

    public int GetHashCode(int[] obj)
    {
        // Average is probably not the best hash for an int array,
        // but I'm lazy right now and this is only for demonstration purposes
        return obj != null ? (int)obj.Average() : 0;
    }
}

并在您的代码中使用它,如下所示:

int[][] connectionList = GetArray().Distinct(new IntArrayComparer()).ToArray();
于 2012-01-30T16:32:23.417 回答
1

你能用IEqualityComparer吗

 public class MyComparer : IEqualityComparer<int []> 
    {     
        bool IEqualityComparer<int[]>.Equals(int[] x, int[] y)     
        {         
             //.. your particular comparison logic goes here
        }
        int IEqualityComparer<int[]>.GetHashCode(int [] obj)     
        {         
            return obj.GetHashCode();     
        }     

    } 

然后像这样调用

var distinctList = myDictionary.Values.Distinct(new MyComparer()).ToList(); 
于 2012-01-30T16:31:58.613 回答