cocogorilla cocogorilla - 2 months ago 6
C# Question

convert query syntax with multiple from and ref back to outer

I'm struggling coming up with the method form of the following query syntax that contains 2

from
clauses and a selection composed from both. It's the reference back to the outer
customerid
and
totaldata
that are throwing me.

//types
DataPair {
int key;
int value;
}
Customer {
int customerid { get; set; }
int totaldata { get; set; }
IEnumerable<DataPair> datapairs { get; set; }
}

var result = from a in customerdata
from b in a.datapairs
select new { a.customerid, a.totaldata, b.key, b.value }

Answer

If I understand correctly, you are seeking for the equivalent method syntax for the provided query syntax.

Multiple from clauses are known to be mapped to the SelectMany extension method. And when the query contains only 2 from clauses, it directly maps to the following SelectMany overload:

public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TCollection>> collectionSelector,
    Func<TSource, TCollection, TResult> resultSelector
)

so the equivalent method syntax would be like this:

var result = customerdata.SelectMany(a => a.datapairs,
    (a, b) => new { a.customerid, a.totaldata, b.key, b.value });