2012-01-30 123 views
2

我正在寻找一种方法从锯齿阵列中获取不同的值。我试图把它放在字典中,但它似乎并没有看到这些值是不同的。任何人有任何解决方案的想法?以下是我迄今为止:C#从锯齿阵列中获取不同的值

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] 

任何想法,我怎么能实现这一点?

+0

它应该是唯一的每个关键或全球? – user7116 2012-01-30 16:17:56

+0

预期产量是多少? – cadrell0 2012-01-30 16:19:43

+0

只有价值需要是唯一的 - 关键不重要。 – 2012-01-30 16:21:39

回答

4

下面是做这件事:

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

虽然它可能是最好创建一个自定义IEqualityComparer<T> - 如建议通过Crab BucketTobias - 而不是创建一个字符串一次性使用的比较。

+1

@dario_ramos看看他的完整问题,他显然知道LINQ。 – 2012-01-30 16:49:02

+0

嗨卢克 - 我认为你是对的,EqualityComparer可能是最好的解决方案,但这确实工作得很好,所以我会坚持这一点。欢呼声 – 2012-01-31 11:38:19

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(); 
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(); 
+0

感谢Tobias--这看起来很有趣。我不知道我现在100%了解它,因此我会继续深入研究它 - 当我如上所示执行时,它将返回一个空数组,因此我将玩弄它并报告回来。非常感谢 – 2012-01-30 16:55:15