Search code examples
c#projection

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


Having trouble trying to project the data in a dictionary <int, IList<string>> to a class that has the structure of

public class MyClass {
   public int Id {get; set;}
   public string Info {get; set;}
}

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

Now myData is an Id which has a list of pieces of info. I need to get it into a List

so that that MyClass list will have values like:

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" 

haven't gotten close to projecting this. Figure to use SelectMany, but haven't gotten anything to match this.


Solution

  • You could do something like this, using System.Linq:

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

    For example:

    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();
    }
    

    Output

    enter image description here