使用linq查询输出列表/其他数据结构

Los*_*der 6 c# linq-to-objects dictionary list map

有没有办法在Generic Collection示例上执行Console.WriteLine():列出a具有:

a.Key[0]: apple
a.Value[0]: 1

a.Key[1]: bold
a.Value[2]: 2
Run Code Online (Sandbox Code Playgroud)

有没有办法写出List内容:Key,Value使用LINQ?

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

foreach (KeyValuePair pair in car) 
{ 
    Console.WriteLine(pair.Key + ' : ' + pair.Value); 
} 
Run Code Online (Sandbox Code Playgroud)

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

dle*_*lev 12

如果你考虑一下,你并不是真的要求查询.查询本质上是询问有关数据的问题,然后以特定方式排列答案.但是,您对该答案所做的与实际生成它的方式是分开的.

在您的情况下,查询的"问题"部分是"我的数据是什么?" (因为你没有应用Where子句,并且"安排"部分是"基于每个项目的值的降序".你得到一个IEnumerable<T>,当被列举时,会吐出你的"答案".

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

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

a.OrderByDescending(x => x.Value).ToList().ForEach(x => { Console.WriteLine(x.Key + ' : ' + x.Value); });
Run Code Online (Sandbox Code Playgroud)

编辑:这篇博文有更多.


Sae*_*ati 9

有一种扩展方法,它本身循环遍历值:

 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.
 });
Run Code Online (Sandbox Code Playgroud)

您还可以使用link的聚合函数将字符串连接在一起:

 Console.WriteLine(myList.Aggregate((a, b) => string.Format("{0}, {1}", a, b)));
Run Code Online (Sandbox Code Playgroud)


Ale*_*der 5

您可以使用 LINQ 构造字符串,然后将其输出到控制台示例:

var s=string.Join(Environment.NewLine, a.Select(x=>string.Format("{0}:{1}",x.Key,x.Value)).ToArray());
Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)