Possible Duplicate:
Nested “from” LINQ query expressed with extension methods
I'm sure this has been asked before, but I honestly couldn't find anything.
I'm curious what the equivalent syntax would be for the following using only built-in Linq extension methods:
var z1 =
from x in xs
from y in ys
select new { x, y };
I can get the same results with this:
var z2 = xs.SelectMany(x => ys.Select(y => new { x, y }));
But it produces different IL code, and the code is a bit convoluted and hard to understand. Is there a cleaner way to do this with extension methods?
Here's my entire test method as written:
private void Test()
{
var xs = new[] { 1D, 2D, 3D };
var ys = new[] { 4D, 5D, 6D };
var z1 =
from x in xs
from y in ys
select new { x, y };
var z2 = xs.SelectMany(x => ys.Select(y => new { x, y }));
}
Here's the [Edit: C# interp of the] IL code (using ILSpy):
private void Test()
{
double[] xs = new double[]
{
1.0,
2.0,
3.0
};
double[] ys = new double[]
{
4.0,
5.0,
6.0
};
var z =
from x in xs
from y in ys
select new
{
x = x,
y = y
};
var z2 = xs.SelectMany((double x) =>
from y in ys
select new
{
x = x,
y = y
});
}
You extend the set of methods that you use for LINQ queries by adding extension methods to the IEnumerable<T> interface. For example, in addition to the standard average or maximum operations, you create a custom aggregate method to compute a single value from a sequence of values.
Cross join is also known as full join.
Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ.
Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.
One way would be:
var z2 = xs.SelectMany(x => ys, (x, y) => new {x, y});
If you really want to use a single LINQ extension method, then another candidate would be Join
, with the outerKeySelector
and innerKeySelector
functions defined such that they will always produce equal values.
var z3 = xs.Join(ys, x => true, y => true, (x, y) => new { x, y });
This will, however, probably give more convoluted IL code than the nested from
solution. Incidentally, MSDN uses the nested from
in its example for a cross join; look at the first code snippet in How to: Perform Custom Join Operations (C# Programming Guide).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With