简体   繁体   中英

LINQ with two From clauses

How to multiply each element from one array to all the element in another array?

Output1 only needs a single foreach statement while Output2 needs a nested for loop.

Is there an equivalent way to write the query into a one liner?

There must be a LINQ method that I'm not aware of

double[] thisCurrency = { 1234, 1000, 50, 20 };
double[] otherCurrency = { 0.01937, 2.1278, 21.014 };

// every element of thisCurrency is multiplied by every element on otherCurrency
var output1 =
    from p in thisCurrency
    from o in otherCurrency
    select p * o;

var output2 = thisCurrency.Select(localCurrency => otherCurrency.Select(oCurrency => oCurrency * localCurrency));

foreach (var currency in output)
{
    Console.WriteLine(currency);
}

Sorry for the newbie question

Your output2 is incorrect because you are not flattening the results of the nested Select . Use SelectMany :

var output2 = thisCurrency.SelectMany(lc => otherCurrency.Select(oc => oc * lc));

Note that you get the output for a Cartesian product of the two lists, ie an equivalent of running two unrestricted nested loops. You would end up with 12 items (4 * 3) in the output sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM