使用Linq选择列表内部列表
使用LINQ如何从List中的List中进行选择
public class Model { public string application { get; set; } public List users { get; set; } } public class Users { public string name { get; set; } public string surname { get; set; } } List list = new List();
我需要选择application =“applicationame”的列表和surname =“surname”的用户到一个列表中。
如果要按applicationname
过滤模型,其余模型按surname
过滤:
List newList = list.Where(m => m.application == "applicationname") .Select(m => new Model { application = m.application, users = m.users.Where(u => u.surname == "surname").ToList() }).ToList();
如您所见,它需要创建新模型和用户列表,因此它不是最有效的方式。
如果您不想过滤用户列表但是至少有一个用户使用给定用户名的用户过滤模型,请使用Any
:
List newList = list .Where(m => m.application == "applicationname" && m.users.Any(u => u.surname == "surname")) .ToList();
您必须在纯LINQ中使用SelectMany
扩展方法或其等效语法。
(from model in list where model.application == "applicationname" from user in model.users where user.surname == "surname" select new { user, model }).ToList();
list.Where(m => m.application == "applicationName" && m.users.Any(u => u.surname=="surname"));
如果你想过滤 TimSchmelter评论的用户,你可以使用
list.Where(m => m.application == "applicationName") .Select(m => new Model { application = m.application, users = m.users.Where(u => u.surname=="surname").ToList() });
在我之前的回答灾难之后,我将尝试别的东西。
List usrList = (list.Where(n => n.application == "applicationame").ToList()); usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));