从两个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方法一样。
更简单的算法应该是:
- 转换为列表列表
- 使用自定义比较器应用distinct
- 重建另一个数组
这看起来像这样:
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; } }
用法:
上述就是C#学习教程:从两个dimentsional数组中删除重复的行分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
[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); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/992478.html