Adding arrays without copying duplicate values ​​in C #

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

Is there a linq way for this. I have a fairly large list of arrays for iteration. 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 will work in date ranges.

+3
source share
1 answer

.Unionwill give you a clear combination of different sequences. Note. If you are working with a custom type, you need to provide overrides for GetHashCode/Equalsinside the class or provide IEqualityComparer<T>for your type when overloaded. For BCL types such as intor DateTime, you'll 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

, .

, , , , 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]);
+8

Source: https://habr.com/ru/post/1787826/


All Articles