gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:02:59 25 4
gpt4 key购买 nike

最快的方法是什么:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com