user1
user1

Reputation: 4131

LINQ: Convert Dictionary<int, List<MyObject>> to List<List<string>>

My Dictionary<int, List<MyObject>> result has..

Key               Value
1                 {"Chicago", 100}
1                 {"Newyork", 200}
2                 {"Minneapolis", 300}

want to convert it to List<List<string>> in below format.

{"Index", "City","Value"},
{1, "Chicago", 100},
{1, "Newyork", 200}
{2, "Minneapolis", 300}

This is what I have achieved so far

 var list = result.Select(rec => new                 
    {
        Index = rec.Key,
        City = rec.Value.Select(rec1 => rec1.City),
        Value = rec.Value.Select(rec1 => rec1.Value)
    }).ToList();

What I am getting is this..

{"Index", "City", "Value"},
{1, System.Linq.Enumerable.WhereSelectListIterator<MyObject, string>, System.Linq.Enumerable.WhereSelectListIterator<MyObject, int>},
{1, System.Linq.Enumerable.WhereSelectListIterator<MyObject, string>, System.Linq.Enumerable.WhereSelectListIterator<MyObject, int>},
{2, System.Linq.Enumerable.WhereSelectListIterator<MyObject, string>, System.Linq.Enumerable.WhereSelectListIterator<MyObject, int>}

May be I am missing Where condition. Please suggest.

public class MyObject
{
        public MyObject(){}
        public string City{get;set;}
        public int Value{get;set;}
}

Upvotes: 0

Views: 533

Answers (4)

dotNET
dotNET

Reputation: 35460

This is what you need:

var Result =  result.SelectMany(r => r.Value.Select(x => new[] { r.Key.ToString(), x.City, x.Value.ToString() }.ToList()));

To prepend column names as the first element of the outer list:

Result.Insert(0, {"Index", "City","Value"}.ToList());

Upvotes: 4

Hieu Le
Hieu Le

Reputation: 1132

Do you need the output like this?

Do you need the output like this?

I have a solution for you. Try it.

Dictionary<int, List<MyObject>> result = new Dictionary<int, List<MyObject>>();

result.Add(1, new List<MyObject>() { new MyObject() { City = "Chicago", Value = 100 }, new MyObject() { City = "Newyork", Value = 200 } });
result.Add(2, new List<MyObject>() { new MyObject() { City = "Minneapolis", Value = 300 } });

var resultYouWant = result.SelectMany(p => p.Value.Select(a => new { Index = p.Key, a.City, a.Value })).ToList();

Upvotes: 1

gmn
gmn

Reputation: 4319

City = rec.Value.Select(rec1 => rec1.City),

That is creating an IEnumerable, not a string. Which is why you get System.Linq.Enumerable.WhereSelectListIterator out of it.

You may be better off using for loops here.

foreach(var kvp in result)
    foreach(var value in kvp)
        //Create string here and add it to your list.

Upvotes: 0

Mukesh Methaniya
Mukesh Methaniya

Reputation: 772

below code is work for you but not getting what is your usecase.

var list = result.Select(rec => new
               {
                  Index = rec.Key,
                  City = rec.Value.City),
                  Value = rec.Value.Value)
            }).ToList();

Upvotes: 0

Related Questions