3

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

1

1 Answer 1

8

.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]);
Sign up to request clarification or add additional context in comments.

3 Comments

What would be the elegant way to union all my ranges without chaining them all in one command.
last, how about a List<int32[]> ?
@geocine, SelectMany method still applies. int[] is an implementer of IEnumerable<T>, List<> is an implementer as well. Same LINQ code that works for int[][] works for the above collection, and would work for IEnumerable<IEnumerable<int>>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.