开发者

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 开发者_StackOverflow社区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.


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();


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜