简体   繁体   English

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

[英]C# Linq - Extract members of list within dictionary

I have a use case for a dictionary like this one 我有一个这样的字典的用例

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

so this collection will hold some hierarchical data like this 所以这个集合会保存一些像这样的分层数据

  • Key 1 关键1
    • Value 1 价值1
    • Value 2 价值2
  • Key 2 键2
    • Value 3 价值3

and I need to get\\project a list of values ignoring the keys, so result would be 并且我需要获取\\投影忽略键的值列表,因此结果将是

  • Value 1 价值1
  • Value 2 价值2
  • Value 3 价值3

on the first attempt I came up with this 在第一次尝试中,我想到了这个

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

Is this any good? 这样好吗

使用SelectMany

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

Note that Dictionary already provides an O(1) way to access its list of values (same as you can access its list of keys) via its Values property 请注意,Dictionary已经提供了O(1)方式,可以通过其Values属性访问其值列表(与您可以访问其键列表相同)

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. 未指定Dictionary.ValueCollection中值的顺序,但与Keys属性返回的Dictionary.KeyCollection中的关联键相同。

The returned Dictionary.ValueCollection is not a static copy; 返回的Dictionary.ValueCollection不是静态副本。 instead, the Dictionary.ValueCollection refers back to the values in the original Dictionary. 相反,Dictionary.ValueCollection会引用回原始Dictionary中的值。 Therefore, changes to the Dictionary continue to be reflected in the Dictionary.ValueCollection. 因此,对Dictionary的更改将继续反映在Dictionary.ValueCollection中。

Getting the value of this property is an O(1) operation. 获取此属性的值是O(1)操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM