简体   繁体   中英

Best way to write this in Linq

How do I refactor this in LINQ. I am working towards embracing good coding practices. My tds object looks like this: tds -> BuildingName(List) -> buildingFloor(string) What I am accomplishing with the nested foreach loop is reading the buildingFloors into a list.

List<string> bname = new List<string>();

foreach (var building in tds) {
    foreach (var x in building.BuildingName) {
        bname.Add(x);
    }
}

您可以使用SelectMany做到这一点,这将使您的商品变平

List<string> bname = tds.SelectMany(b => b.BuildingName).ToList();

使用Enumerable.SelectMany可以使列表变平,例如:

List<string> bname = tds.SelectMany(r=> r.BuildingName).ToList();

What you're looking for is SelectMany.

var bname = buildings.SelectMany(b => b.BuildingName);

Note, if you're going to be enumerating over the result multiple times with foreach then you will probably want to ToList() it, so you have a hard list rather than an enumerable that is executed every time you enumerate it.

var bname = buildings.SelectMany(b => b.BuildingName).ToList();

something like this I suppose:

var bname = tds.SelectMany(x => x.BuildingName);

And if you need a List call .ToList() at the end

var bname = tds.Select( x=> x.buildingName).ToList() ;

编辑:通勤上班时,我没有看到内部foreach,的确是

var bname = tds.SelectMany(x=> x.BuildingName).ToList();

using query-syntax:

List<string> bname =
  (from building in tds
  from x in building.BuildingName
  select x)
  .ToList()

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