简体   繁体   中英

Remove element from last level of nested list C# LINQ

I have an entity with multiple levels of nested lists - Is there a way to remove element from last level using LINQ (without any nested foreach) - remove Dosage with id = X from strength with id = Y from route with id = Z from drug with id = Q? (assume XYZQ are ints) I've provided my entity structure below.

var entity: List<Drug>;
Drug {
    int id;
    List<Route> routes;
}

Route {
    int id;
    List<Strength> strengths;
}

Strength {
    int id;
    List<Dosage> dosages;
}

Dosage {
    int id;
}

Try this:

drugList.Where(x => x.id == Q).FirstOrDefault().routes.Where(x => x.id == Z).FirstOrDefault().strengths.Where(x => x.id == Y).FirstOrDefault().dosages.RemoveAt(X);

With the Q,Z,Y,X as the index values from your post.

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