C# Linq - 提取字典中列表的成员

C# Linq - Extract members of list within dictionary

我有这样一个字典的用例

var foo = new Dictionary<string, List<string>>()

所以这个集合将包含一些像这样的分层数据

我需要 get\project 忽略键的值列表,所以结果将是

第一次尝试时我想到了这个

IReadOnlyList<string> bar = foo.Select(r => r.Value.Select(x => x.ToString()))
                             .Select(r => r.ToString())
                             .ToList();

这样好吗?

使用SelectMany:

foo.SelectMany(x => x.Value).ToList();

请注意,Dictionary 已经提供了一种 O(1) 方法来通过其值访问其值列表(与访问其键列表相同)属性

The order of the values in the Dictionary.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary.KeyCollection returned by the Keys property.

The returned Dictionary.ValueCollection is not a static copy; instead, the Dictionary.ValueCollection refers back to the values in the original Dictionary. Therefore, changes to the Dictionary continue to be reflected in the Dictionary.ValueCollection.

Getting the value of this property is an O(1) operation.

https://msdn.microsoft.com/en-us/library/ekcfxy3x(v=vs.110).aspx