使用 linq 查询输出列表/其他数据结构
有没有办法在通用集合上执行 Console.WriteLine() 例子: 列表 a 有:
a.Key[0]: apple
a.Value[0]: 1
a.Key[1]: bold
a.Value[2]: 2
有没有办法使用 LINQ 写出列表内容:键、值?
a = a.OrderByDescending(x => x.Value));
foreach (KeyValuePair pair in car)
{
Console.WriteLine(pair.Key + ' : ' + pair.Value);
}
我想写一个 Linq / 查询而不是 foreach... 是否可以?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你仔细想想,你并不是真的在询问。查询本质上是询问有关数据的问题,然后以特定方式排列答案。不过,您对该答案所做的操作与实际生成它是分开的。
在您的情况下,查询的“问题”部分是“我的数据是什么?” (因为您没有应用Where子句),“排列”部分是“根据每个项目的值按降序排列”。您会得到一个
IEnumerable
,在枚举时,它会吐出您的“答案”。此时,您实际上需要对答案执行某些操作,因此您使用 foreach 循环对其进行枚举,然后对每个项目执行您需要的任何操作(就像您在问题中所做的那样)。认为这是一个完全合理的方法,它清楚地表明了正在发生的事情。
如果您绝对必须使用 LINQ 查询,则可以执行以下操作:
编辑:此 博客文章 有更多内容。
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:
EDIT: This blog post has more.
有一个扩展方法,它本身循环遍历值:
您也可以使用 link 的聚合函数将字符串连接在一起:
There is an extension method which in itself loops over the values:
Also you can use aggregate functions of link to concatenate strings together:
您可以使用 LINQ 构造字符串,然后将其输出到控制台
例子:
You can construct string using LINQ and then outputs it to console
Example: