从两个dimentsional数组中删除重复的行

假设我有二维数组代表简单矩阵

int[,] matrix= new int[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } }; 

它看起来像那样

 1 2 3 4 1 2 7 8 

有没有办法使用LINQ删除重复的行,并使数组看起来像这样?

 1 2 3 4 7 8 

这不是真正的Linq,但你可以定义一些辅助方法,就像它们是Linq方法一样。

更简单的算法应该是:

  1. 转换为列表列表
  2. 使用自定义比较器应用distinct
  3. 重建另一个数组

这看起来像这样:

 public static class MyExtensions { public static IEnumerable> ToEnumerableOfEnumerable(this T[,] array) { int rowCount = array.GetLength(0); int columnCount = array.GetLength(1); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { var row = new List(); for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { row.Add(array[rowIndex, columnIndex]); } yield return row; } } public static T[,] ToTwoDimensionalArray(this List> 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; } } 

自定义列表比较器(从Jon Skeet的答案中复制) :

 public class ListEqualityComparer : IEqualityComparer> { public bool Equals(List x, List y) { return x.SequenceEqual(y); } public int GetHashCode(List obj) { int hash = 19; foreach (var o in obj) { hash = hash * 31 + o.GetHashCode(); } return hash; } } 

用法:

 [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()) .ToList() .ToTwoDimensionalArray(); } } 
 int[,] list = new int[,] { { 1, 2 }, { 3, 4 }, { 1, 2 }, { 7, 8 } }; List> newList = new List>(); bool dupFound; for (int i = 0; i < list.Length; i++) { dupFound = false; for (int a = 0; a < list.Length; i++) { if ((i != a) && list[a, 0] == list[i, 0] && list[a, 1] == list[i, 1]) { dupFound = true; break; } } if (!dupFound) { var nonDup = new KeyValuePair(list[i,0], list[i,1]); newList.Add(nonDup); } }