Using Linq select list inside list

前端 未结 4 1511
清歌不尽
清歌不尽 2021-02-04 04:08

Using LINQ how to select from a List within a List

public class Model
{
    public string application { get; set; }

    public List users { get; se         


        
4条回答
  •  失恋的感觉
    2021-02-04 04:46

    If you want to filter the models by applicationname and the remaining models by 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();
    

    As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.

    If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any:

    List newList = list
        .Where(m => m.application == "applicationname"
                &&  m.users.Any(u => u.surname == "surname"))
        .ToList();
    

提交回复
热议问题