c# - 在 C# 中添加数组而不复制重复值

标签 c# .net arrays union intersection

最快的方法是什么:

var firstArray = Enumerable.Range(1, 10).ToArray(); // 1,2,3,4,5,6,7,8,9,10
var secondArray = Enumerable.Range(9, 3).ToArray(); //                 9,10,11,12
var thirdArray = Enumerable.Range(2, 3).ToArray();  //   2,3,4,5
//add these arrays expected output would be            1,2,3,4,5,6,7,8,9,10,11,12

有没有一种 linq 方法可以做到这一点。我有一大堆要迭代的数组。另一个例子

var firstArray = Enumerable.Range(1, 10).ToArray(); // 1,2,3,4,5,6,7,8,9,10
var secondArray = Enumerable.Range(12, 1).ToArray(); //                     12,13
//add these arrays expected output would be            1,2,3,4,5,6,7,8,9,10,12,13

注意:我更喜欢适用于日期范围的函数。

最佳答案

.Union将为您提供各种序列的独特组合。注意:如果您使用的是自定义类型,则需要为 GetHashCode/Equals 提供覆盖在类内或提供 IEqualityComparer<T>为您的类型重载。对于 BCL 类型,例如 intDateTime ,你会没事的。

例子:

var sequence = Enumerable.Range(0,10).Union(Enumerable.Range(5,10));
// should result in sequence of 0 through 14, no repeats

编辑

What would be the elegant way to union all my ranges without chaining them all in one command.

如果您有一系列序列,可以是列表的集合,也可以是锯齿状数组,您可以使用 SelectMany方法连同 Distinct .

int[][] numberArrays = new int[3][];
numberArrays[0] = new int[] { 1, 2, 3, 4, 5 };
numberArrays[1] = new int[] { 3, 4, 5, 6, 7 };
numberArrays[2] = new int[] { 2, 4, 6, 8, 10 };

var allUniqueNumbers = numberArrays.SelectMany(i => i).Distinct();

否则,您可能会考虑创建自己的扩展方法来处理此问题。

public static class MyExtensions
{
    public static IEnumerable<T> UnionMany<T>(this IEnumerable<T> sequence, params IEnumerable<T>[] others)
    {
        return sequence.Union(others.SelectMany(i => i));
    }
}

//

var allUniques = numberArrays[0].UnionMany(numberArrays[1], numberArrays[2]);

关于c# - 在 C# 中添加数组而不复制重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799654/

相关文章:

c - 为什么我的指针运算在这个数组中失败

arrays - 异步并行重复条目

c - 在 C 中求和并查找数组的非零项

c# - 在不使用另一个变量的情况下交换两个数字

c# - 使用linq查找匹配多个行值的外键

c# - 使连接的套接字在.BeginReceive 之后立即接受新消息?

.net - Random.Next - 我不明白

c# - IndexOutOfRangeException 由于一些奇怪的原因

c# - 如何比较Azure资源配置

.net - IObservable<double>.Average 应该如何工作?