Mit*_*tya 5 c# row multidimensional-array
假设我有代表简单矩阵的二维数组
int[,] matrix= new int[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } };
Run Code Online (Sandbox Code Playgroud)
看起来像那样
1 2
3 4
1 2
7 8
Run Code Online (Sandbox Code Playgroud)
有什么方法可以使用LINQ删除重复的行并使数组看起来像这样吗?
1 2
3 4
7 8
Run Code Online (Sandbox Code Playgroud)
这实际上不是Linq,但是您可以定义一些辅助方法,就像它们是Linq方法一样。
更简单的算法应为:
看起来像这样:
public static class MyExtensions
{
public static IEnumerable<List<T>> ToEnumerableOfEnumerable<T>(this T[,] array)
{
int rowCount = array.GetLength(0);
int columnCount = array.GetLength(1);
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
var row = new List<T>();
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
row.Add(array[rowIndex, columnIndex]);
}
yield return row;
}
}
public static T[,] ToTwoDimensionalArray<T>(this List<List<T>> tuples)
{
var list = tuples.ToList();
T[,] array = null;
for (int rowIndex = 0; rowIndex < list.Count; rowIndex++)
{
var row = list[rowIndex];
if (array == null)
{
array = new T[list.Count, row.Count];
}
for (int columnIndex = 0; columnIndex < row.Count; columnIndex++)
{
array[rowIndex, columnIndex] = row[columnIndex];
}
}
return array;
}
}
Run Code Online (Sandbox Code Playgroud)
定制列表比较器(从Jon Skeet的答案复制):
public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> x, List<T> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<T> obj)
{
int hash = 19;
foreach (var o in obj)
{
hash = hash * 31 + o.GetHashCode();
}
return hash;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var array = new[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } };
array = array.ToEnumerableOfEnumerable()
.Distinct(new ListEqualityComparer<int>())
.ToList()
.ToTwoDimensionalArray();
}
}
Run Code Online (Sandbox Code Playgroud)