C#:使用 LINQ 将字典 <int, IList<string>> 投影到 class 的平面列表

C# : Projection of a dictionary<int, IList<string>> to a flat list of class using LINQ

尝试将 dictionary <int, IList<string>> 中的数据投影到具有

结构的 class 时遇到问题
public class MyClass {
   public int Id {get; set;}
   public string Info {get; set;}
}

private Dictionary<int, IList<string>> myData;

现在 myData 是一个包含信息片段列表的 Id。我需要将其放入列表

这样 MyClass 列表将具有如下值:

Id = 1, Info = "line 1"
Id = 1, Info = "line 2"
Id = 1, Info = "line 3"
Id = 2, Info = "something else"
Id = 2, Info = "another thing" 

还没有接近预测这个。图为使用 SelectMany,但还没有找到任何与之相匹配的东西。

这是您要找的吗?

List<MyClass> Project(Dictionary<int, IList<string>> data)
{
    List<MyClass> result = new List<MyClass>();
    foreach (int key in data.Keys)
        foreach (string s in data[key])
            result.Add(new MyClass { Id = key, Info = s });
    return result;
}

我们的想法是遍历每个 int,并在其中遍历与该 int 关联的每个字符串。并将这些组合(整数和字符串)中的每一个添加到结果中。

你可以这样做,使用 System.Linq:

List<MyClass> classList = myData.Keys
    .SelectMany(key => myData[key], (key, s) => new MyClass {Id = key, Info = s})
    .ToList();

例如:

static void Main(string[] args)
{
    // Start with a dictionary of Ids and a List<string> of Infos
    var myData = new Dictionary<int, List<string>>
    {
        {1, new List<string> {"line 1", "line 2", "line 3" } },
        {2, new List<string> {"something else", "another thing" } },
    };

    // Convert it into a list of MyClass objects
    var itemList = myData.Keys
        .SelectMany(key => myData[key], (key, s) => new MyClass { Id = key, Info = s })
        .ToList();

    // Output each MyClass object to the Console window
    Console.WriteLine("The list of MyClass contains the following objects:");
    foreach(var item in itemList)
    {
        Console.WriteLine($"MyClass: Id = {item.Id}, Info = {item.Info}");
    }

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

输出