简体   繁体   中英

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?

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
  })
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM