Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to store string values in dictionary object with comma seperated in c# out of a list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading