使用linq查询输出列表/其他数据结构 [英] Output a list/other data structure using linq query

查看:71
本文介绍了使用linq查询输出列表/其他数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在通用集合上执行Console.WriteLine()例子:列出一个具有

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

有没有办法写出列表内容:使用LINQ的键,值?

Is there a way to write out the List contents: Key, Value using LINQ?

a = a.OrderByDescending(x => x.Value));

a = a.OrderByDescending(x => x.Value));

foreach (KeyValuePair pair in car) 
{ 
    Console.WriteLine(pair.Key + ' : ' + pair.Value); 
} 

我想写一个Linq/查询而不是foreach ...是否可以?

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.

在您的情况下,查询的问题"部分是我的数据是什么?"(因为您未应用Where子句),并且排列"部分是根据每个项目的值按降序排列".您将得到一个 IEnumerable< T> ,该名称在枚举时将吐出您的答案".

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".

这时,您实际上需要对答案做些什么,因此您可以使用 foreach 循环枚举它,然后对每个项目执行所需的任何操作(就像您在问题中所做的一样).)我认为这是一种非常合理的方法,可以清楚说明正在发生的事情.

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.

如果绝对必须使用LINQ查询,则可以执行以下操作:

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); });

编辑:此 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆