I need to convert list into dictionary based on key. I have list a like as below id, name and so on in List object List items.
List<MyData> lst = new List<MyData>();
MyData objMyData = new MyData();
MyData objMyData1 = new MyData();
MyData objMyData2 = new MyData();
objMyData.Id = 1;
objMyData.Name = "Test";
lst.Add(objMyData);
objMyData1.Id = 2;
objMyData1.Name = "Test2";
lst.Add(objMyData1);
objMyData2.Id = 1;
objMyData2.Name = "Test3";
lst.Add(objMyData2);
As per my requirement I need to create a dictionary object from it in this format.
Dictionary<int, string>.
Where key is int id of item and value in string of item.name with comma seperated one. it should look like
Dictionary<1, "Test, test3")
Dictionary<2, "Test2")
I’m trying below code, but stuck.
var dict = lst.ToLookup(x => x.Id)
.ToDictionary(x => x.Key, x=>x.ToList());
here instead of x.ToList(), my requirement is to get list.name with comma separated based on key.
>Solution :
.ToList() will return the grouped list of MyData.
You should select the Name and combine it into a string.
var dict = lst.ToLookup(x => x.Id)
.ToDictionary(x => x.Key, x => String.Join(",", x.Select(y => y.Name)));