Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a list/other data structure using linq query

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?

like image 881
Loser Coder Avatar asked Jul 07 '11 05:07

Loser Coder


1 Answers

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.

like image 109
dlev Avatar answered Nov 10 '22 00:11

dlev