User
User

Reputation: 3274

Combining Two Arrays & Projecting

Supposing I have the constructor

public SomeObject(string first, string second);

and two string[] arrays

string[] arrayOne = new[] { firstOne, firstTwo };
string[] arrayTwo = new[] { secondOne, secondTwo, secondThree};

how can I return an IEnumerable or IList each element of which is a new SomeObject composed of a combination of both array's elements? Currently, I am using

IEnumerable<SomeObject> newEnumerable = from stringOne in arrayOne from stringTwo in arrayTwo select new SomeObject(stringOne, stringTwo);

but I would prefer something like

IEnumerable<SomeObject> newEnumerable = arrayOne.Select(stringOne => arrayTwo.Select(stringTwo => new SomeObject(stringOne, stringTwo));

but this last one returns IEnumerable<IEnumerable<SomeObject>> which, of course, is not what I want.

Upvotes: 1

Views: 53

Answers (2)

dlev
dlev

Reputation: 48596

You can flatten the result from the second query using SelectMany():

var newEnumerable =
    arrayOne.Select(stringOne => arrayTwo.Select(stringTwo => new SomeObject(stringOne, stringTwo)).SelectMany(x => x);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502816

It's not really clear what you want - if you're just looking for a version of the first query which doesn't use query expression syntax, you want:

var query = arrayOne.SelectMany(x => arrayTwo, (a, b) => new SomeObject(a, b));

That's basically what your query expression is being expanded to anyway.

If that's not what you want, please make your question clearer. If you want an array at the end, just call ToArray:

var array = arrayOne.SelectMany(x => arrayTwo, (a, b) => new SomeObject(a, b))
                    .ToArray();

Upvotes: 1

Related Questions