C#从锯齿状数组中获取不同的值
本文关键字:获取 锯齿状 数组 | 更新日期: 2023-09-27 18:21:49
我正在寻找一种从锯齿状数组中获取不同值的方法。我试着把它放进字典里,但它似乎并不认为这些值是不同的。有人有解决方案的想法吗?以下是我目前所拥有的:
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]
我试着把它加到字典里去了。我试着在添加重复值时捕捉它们,但没有成功,所以尝试添加.Dispinct(),但也不高兴
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]
有没有想过我该如何做到这一点?
这里有一种方法:
var distinctList = connectionList.GroupBy(x => string.Join(",", x))
.Select(g => g.First())
.ToList();
尽管创建一个自定义的IEqualityComparer<T>
可能更可取——正如Crab Bucket和Tobias所建议的那样——而不是创建一个用于比较的一次性字符串。
使用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();
您能使用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();