如何使用LINQ将字典的键和值组合到一个列表中? [英] How do I combine the keys and values of a Dictionary into one List using LINQ?

查看:60
本文介绍了如何使用LINQ将字典的键和值组合到一个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其中的键是一个字符串,值是一个与该键对应的字符串列表.我想显示字典中的所有键,并将与该键关联的值标签在该键下方.像这样:

I have a dictionary, where the key is a string and the value is a list of strings that correspond to that key. I would like to display all of the keys in the dictionary, with the values associated with that key tabbed in underneath that key. Something like this:

Key 1
    Value 1
    Value 2
    Value 3
Key 2
    Value 1
    Value 2

在C#2.0中,我会这样做(valuesDictionary):

In C# 2.0, I would do that like this (values is the Dictionary):

StringBuilder sb = new StringBuilder();
foreach(KeyValuePair<string, List<string>> pair in values)
{
    sb.AppendLine(pair.Key);
    foreach(string item in pair.Value)
    {
        sb.AppendLine('\t' + item);
    }
}

我将如何使用LINQ进行等效操作?似乎应该有可能,但是我不知道该怎么做.

How would I do the equivalent using LINQ? It seems like it should be possible, however I can't figure out how to do it.

如果使用values.SelectMany(p => p.Values),则最终结果中只会包含值,而不是键中的值.

If I use values.SelectMany(p => p.Values), then only the values will be in the final result, not the keys as well.

我想到的任何其他解决方案都具有类似的局限性.

Any other solution that I've thought of has a similar limitation.

推荐答案

C#中的解决方案

以下是使用集合扩展方法的解决方案:

A Solution in C#

Here is a solution using the aggregate extension method:

string result = values.Aggregate("",
                  (keyString, pair) =>
                    keyString + "\n" + pair.Key + ":"
                      + pair.Value.Aggregate("",
                          (str, val) => str + "\n\t" + val)
                  );

在C#中没有用于聚合子句的LINQ语法(但显然在 Visual Basic (用于某些预定义功能).

There is no LINQ syntax for the aggregate clause in C# (but apparently there is in Visual Basic for some predefined functions).

此解决方案可能看起来有些复杂,但是聚合方法非常有用.

This solution might look somewhat complex, but the aggregate method is quite useful.

它的工作原理是:如果您有List<int>,则可以将所有值组合为单个汇总值.

It works like this: If you have a List<int> you can combine all values into a single aggregate value.

Select方法相反,该方法不会修改列表的长度.或Where方法可以缩小列表,但仍然保留列表(而不是单个值).

That is in contrast to the Select method, which doesn't modify the length of the list. Or the Where method, which does shrink the list, but it still remains a list (instead of a single value).

例如,如果您有一个列表{1, 2, 3, 4},则可以将它们合并为一个单个值,如下所示:

For example, if you have a list {1, 2, 3, 4} you can combine them into a single value like this:

int[] xs = {1, 2, 3, 4};
int sum = xs.Aggregate(0, (sumSoFar, x) => sumSoFar + x);

因此您将两个值赋予Aggregate方法;种子值和合并器"函数:

So you give two values to the Aggregate method; a seed value and a 'combiner' function:

  • 您开始使用单个种子值(在这种情况下为0)进行汇总.
  • 将为列表中的每个值调用组合器函数.
    第一个参数是到目前为止的计算结果(第一次为零,以后将具有其他值),并将其与值x组合.
  • You start aggregating with a single seed value (0 in this case).
  • Your combiner function gets called for each value in the list.
    The first argument is the computed result so far (zero the first time, later this will have other values), and it combines it with the value x.

这就是Aggregate方法在List<int>上的工作方式.它在KeyValuePair<string, List<string>>上的工作原理相同,只是类型不同.

That's in short how the Aggregate method works on List<int>. It works the same on KeyValuePair<string, List<string>>, but just with different types.

这篇关于如何使用LINQ将字典的键和值组合到一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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