PSR PSR - 1 year ago 132
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
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download