【问题标题】:C# - Convert Dictionary of Lists to List of Tuples with LINQC# - 使用 LINQ 将列表字典转换为元组列表
【发布时间】:2020-07-13 05:33:15
【问题描述】:

我有一本字典:

Dictionary<int, List<(byte Id, string name)

这本词典的结构类似于:

{
[1, {(1, "Leo"), (2, "Messi")}]
[2, {(3, "Cris"), (4, "Ronaldo")}]
}

如何使用 LINQ 将其转换为以下内容:

List<(int, byte)>

所以结构变成这样:

{
(1,1),
(1,2),
(2,3),
(2,4),
}

TIA。

【问题讨论】:

  • 到目前为止您尝试过什么?向我们展示你的努力。
  • 查看SelectMany,这是扁平化内部集合的方法。

标签: c# list linq dictionary


【解决方案1】:

假设你的字典是这样声明的

var dict = new Dictionary<int, List<(byte Id, string name)>>
{
    {1, new List<(byte Id, string name)> {(1, "Leo"), (2, "Messi")}},
    {2, new List<(byte Id, string name)> {(3, "Cris"), (4, "Ronaldo") }}
};

您可以使用SelectMany 方法将其转换为List&lt;(int, byte)&gt;

var list = dict.SelectMany(kvp => kvp.Value, (pair, tuple) => (pair.Key, tuple.Id)).ToList();

【讨论】:

  • 谢谢帕维尔,这正是我想要的!
猜你喜欢
  • 2013-04-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 2017-06-07
相关资源
最近更新 更多