Delete duplicate rows from two dimentsional array

前端 未结 2 539
渐次进展
渐次进展 2021-01-01 03:06

Let\'s say I have two dimensional array that represents simple matrix

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

2条回答
  •  迷失自我
    2021-01-01 03:46

    This is not really Linq, but you can define some helper method as if they were Linq methods.

    The simpler algorithm should be:

    1. Convert to a list of list
    2. Apply a distinct with a custom comparer
    3. Rebuild another array

    This looks like this:

    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;
        }
    }
    

    The custom List comparer (copied from a Jon Skeet's answer):

    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;
        }
    }
    

    The usage :

    [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();
        }
    }
    

提交回复
热议问题