开发者

Adding arrays without copying duplicate values in C#

开发者 https://www.devze.com 2023-02-06 13:46 出处:网络
What is the fastest way to do this: var firstArray = Enumerable.Range(1, 10).ToArray(); // 1,2,3,4,5,6,7,8,9,10

What is the fastest way to do this:

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 t开发者_JS百科hirdArray = 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

Is there a linq way to do this. I quite have a huge list of array to iterate. another example

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

Note: I prefer a function that would work on date ranges.


.Union will give you the distinct combination of various sequences. Note: if you are working with a custom type, you will need to provide overrides for GetHashCode/Equals inside the class or provide an IEqualityComparer<T> for your type in an overload. For BCL types such as int or DateTime, you will be fine.

Example:

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

Edit

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

If you have a sequence of sequences, be it a collection of lists, perhaps a jagged array, you can use the SelectMany method along with 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();

Otherwise, you might consider creating your own extension method that could handle this.

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]);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号