使用 linq 展平 KeyValuePair<string, List<string>> 对象

ash*_*eek 1 c# linq dictionary

因此,基本上我在 C# 中实现 MultiMap,并且采用了显而易见的方法:使用使用 List 作为值的 Dictionary 对象。接下来,我需要返回键值对的扁平列表:List<KeyValuePair<TKey, TValue>>。使用循环来完成这件事还不错,但我很好奇如何使用 Linq 来完成这件事。

我使用 SelectMany 函数接近了,但我不太清楚如何从 A 点到 B 点。这是我的代码,无需 Linq 即可完成此操作(减去您不关心的其他位)。

public class MultiDict<TKey, TValue>
{
    private Dictionary<TKey, List<TValue>> _dict = new Dictionary<TKey, List<TValue>>();

    public void AddValue(TKey key, TValue val)
    {
        List<TValue> list;
        if (_dict.ContainsKey(key))
        {
            list = _dict[key];
        }
        else
        {
            list = new List<TValue>();
            _dict.Add(key, list);
        }
        list.add(val);
    }

    public KeyValuePair<TKey, TValue>[] Flattened() 
    {
        var flattened = new List<KeyValuePair<TKey, TValue>>();
        foreach (var pair in _dict)
        {
            //pair.Value is actually a List<TValue> object that we have to
            //    iterate through as well
            foreach (var val in pair.Value)
            {
                flattened.add(new KeyValuePair<TKey, TValue>(pair.Key, val));
            }
        }

        return flattened.ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

所以如果我像这样使用它:

var multiDict = new MultiDict<int, string>();
multiDict.Add(1, "King");
multiDict.Add(1, "Boomy");
multiDict.Add(3, "Aang");

var results = multiDict.Flattened();
Run Code Online (Sandbox Code Playgroud)

我应该在results.

小智 5

选择多个将展平嵌套数组。Value.Select 为子列表中的每个项目创建一个 KVP,然后选择多个将嵌套数组转换为扁平集合。

public KeyValuePair<TKey, TValue>[] Flattened()
{
    return _dict.SelectMany(x => x.Value.Select(v => new KeyValuePair<TKey, TValue>(x.Key, v))).ToArray();
}
Run Code Online (Sandbox Code Playgroud)