如何从int [] []删除重复 [英] How to remove duplicates from int[][]

查看:104
本文介绍了如何从int [] []删除重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组的数组 - 使用VSTO,其中每个元素是指开始,大约在Excel中选择信息最终选择位置

I have an array of arrays - information about selection in Excel using VSTO, where each element means start and end selection position.

例如,

int[][] selection = {
new int[] { 1 }, // column A
new int[] { 6 }, // column F
new int[] { 6 }, // column F
new int[] { 8, 9 } // columns H:I
new int[] { 8, 9 } // columns H:I
new int[] { 12, 15 } // columns L:O
};

能否请你帮我找到一种方法,也许使用LINQ或扩展方法,以删除重复的元素呢?我的意思是:˚F˚F H:我 H:我

推荐答案

如果你想使用一个纯粹的LINQ /扩展方法解决方案,那么你需要定义自己的执行的IEqualityComparer 数组/序列。 (除非我缺少明显的东西,有一个在BCL没有pre-现有阵列或序列的比较器)。这是不是非常难然而 - 这里是应该做的工作pretty很好的一个例子:

If you want to use a pure LINQ/extension method solution, then you'll need to define your own implementation of IEqualityComparer for arrays/sequences. (Unless I'm missing something obvious, there's no pre-existing array or sequence comparer in the BCL). This isn't terribly hard however - here's an example of one that should do the job pretty well:

public class SequenceEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
    public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
    {
        return Enumerable.SequenceEqual(x, y);
    }

    // Probably not the best hash function for an ordered list, but it should do the job in most cases.
    public int GetHashCode(IEnumerable<T> obj)
    {
        int hash = 0;
        int i = 0;
        foreach (var element in obj)
            hash = unchecked((hash * 37 + hash) + (element.GetHashCode() << (i++ % 16)));
        return hash;
    }
}

这样做的好处是,你可以然后只需调用下面,以消除任何重复的阵列。

The advantage of this is that you can then simply call the following to remove any duplicate arrays.

var result = selection.Distinct(new SequenceEqualityComparer<int>()).ToArray();

希望有所帮助。

这篇关于如何从int [] []删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆