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 开发者_StackOverflow社区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.
There is an extension method which in itself loops over the values:
myList.ForEach(a => {
// You have access to each element here, but if you try to debug, this is only one function and won't be iterated in debug mode.
});
Also you can use aggregate functions of link to concatenate strings together:
Console.WriteLine(myList.Aggregate((a, b) => string.Format("{0}, {1}", a, b)));
You can construct string using LINQ and then outputs it to console Example:
var s=string.Join(Environment.NewLine, a.Select(x=>string.Format("{0}:{1}",x.Key,x.Value)).ToArray());
Console.WriteLine(s);
精彩评论