LINQ, joining results of two methods
I want to create a flat result set from the results of two methods in which the results of the first are the arguments for the second.
For example, method 1 returns 1,2,3
and I want to feed each int into method 2, which just returns 4,5,6
every time.
So I expect back a resultset like 1:4, 1:5, 1:6, 2:4, 2:5, 2:6, 3:4, 3:5,开发者_开发百科 3:6
If possible, I want to do this in a single LINQ query (pref c#). I hope this explanation is clear and someone can help me.
EDIT:
I shouldn't have asked. This is easy. For anyone else who needs it:
int[] aList = new int[] { 1, 2, 3 };
var enumerable = from a in aList
from b in GetResult(a)
select new { x = a, y = b };
Sounds like you're looking for SelectMany.
Func<IEnumerable<int>> method2 = () => new [] {4,5,6};
(new [] {1,2,3})
.SelectMany(m1Arg => method2().Select(m2arg => string.Format("{0}:{1}",m1Arg,m2arg)));
In query syntax, it's two *from*s as in
var q = from a in List
from b in List2
select a,b...
Using LINQ expressions
void Main()
{
var method1 = new[] {1,2,3};
var method2 = new[] {4,5,6};
var res = from m in method1
from m2 in method2
select String.Format("{0}:{1}", m, m2);
foreach (var x in res) {
Console.Out.WriteLine(x);
}
}
精彩评论