WorksOnMyLocal
WorksOnMyLocal

Reputation: 1689

Convert a Dictionary<string,List<string>> into a List<string,string>

I am using dictionary Dictionary<string,List<string>> which will have values like

Key        ||        Values
1                     a,b,c
2                     d,e

I want to convert this dictionary into a list of Objects of type MyClass

MyClass has two properties i.e.

Class MyClass{
 public string ID { get; set; }
 public string Name { get; set; }
}

Which would be

1 ,  a
1 ,  b
1 ,  c
2 ,  d
2 ,  e

I have tried some things like using Keys.Tolist and Values.ToList but have not been successful in getting what i need.

I am aware that this can be done using a loop, but i prefer not using it since the data that i will be dealing with will be in hundreds of thousands i.e. hundreds of thousands of keys and tens of millions of values.

Can someone help me in finding an efficient way to deal with this?

Upvotes: 0

Views: 989

Answers (2)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

You can do that in one line and flatten a dictionary values using SelectMany method, but it's still using a loop under the hood

var dict = new Dictionary<string, List<string>>
{
    { "1", new List<string> { "a", "b", "c" } },
    { "2", new List<string> { "d", "e" } }
};

var result = dict
    .SelectMany(kvp => kvp.Value, (kvp, s) => new MyClass { ID = kvp.Key, Name = s })
    .ToList();

Upvotes: 4

Krystian Sitek
Krystian Sitek

Reputation: 588

You can do it by flattening your list with strings with select statement from LINQ. First, you iterate over dictionary collection, and then inside you iterate over a list of strings and create new objects from it. Below I placed an example that should help you understand it.

    public class MyClass
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    var list = new List<string>
    {
        "a",
        "b",
        "c"
    };

    var list2 = new List<string>
    {
        "d",
        "e"
    };

    var dict = new Dictionary<string,List<string>>();
    dict.Add("1", list);
    dict.Add("2", list2);

    var x = dict.SelectMany(x => x.Value.Select(z => new MyClass
    {
        Id = x.Key,
        Name = z
    })).ToList();

Upvotes: 1

Related Questions