is there a way to do a Console.WriteLine() on a Generic Collection example: List a has:
a.Key[0]: apple
a.Value[0]: 1
a.Key[1]: bold
a.Value[2]: 2
Is there a way to write out the List contents: Key, Value using LINQ?
a = a.OrderByDescending(x => x.Value));
foreach (KeyValuePair pair in car)
{
Console.WriteLine(pair.Key + ' : ' + pair.Value);
}
Instead of the foreach I want to write a Linq / query... is it possible?
If you think about it, you're not really asking for a query. A query is essentially asking a question about data, and then arranging the answer in a particular manner. What you do with that answer is separate from actually generating it, though.
In your case, the "question" part of the query is "what is my data?" (since you didn't apply a Where clause,) and the "arrangement" part is "in descending order based on the Value of each item". You get an IEnumerable<T>
which, when enumerated, will spit out your "answer".
At this point, you actually need to do something with the answer, so you enumerate it using a foreach
loop, and then perform whatever actions you need on each item (like you do in your question.) I think this is a perfectly reasonable approach, that makes it clear what's going on.
If you absolutely must use a LINQ query, you can do this:
a.OrderByDescending(x => x.Value).ToList().ForEach(x => { Console.WriteLine(x.Key + ' : ' + x.Value); });
EDIT: This blog post has more.
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