PSR PSR - 2 months ago 28
C# Question

Group by entities using LINQ

I have entities like this

class Test
{
string Name;
IList<SubTest> subTest;
}

class SubTest
{
string Id;
string value;
}


from a server I will get result of
IEnumerable<Test>
.
I want ot convert this result to SelectListItem so that I can bind this to mvc dropdown list.

Something like this

new SelectListItem(){Group=Test.Name, Value=SubTest.Id, Text= subTest.Value}


How can I get this result using linq?

Answer

Use Select() and SelectMany() to transform the data into SelectListItem

System.Collections.Generic.IEnumerable<Test> lResultFromServer = ...;

var lSelectListItems = lResultFromServer.SelectMany(s =>
  s.subTest.Select(st => new System.Web.Mvc.SelectListItem {
    Group = new System.Web.Mvc.SelectListGroup {Name = s.Name},
    Value = st.Id,
    Text = st.value
  })
);