如果列包含重复值,则删除2D数组中的行

时间:2014-01-21 22:08:18

标签: c# multidimensional-array duplicates

我正在研究Excel中有关2D数组的问题:如果单个列包含重复值,则可以删除行。我怎样才能在C#中完成同样的事情?

请参阅此内容以供参考。仅当整行包含重复值时,它才会删除。我需要相同的东西,除非只有一个列包含重复项,否则应删除该行。

链接: Delete duplicate rows from two dimentsional array

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

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

用法:

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

0 个答案:

没有答案