Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq select list inside list

Tags:

Using LINQ how to select from a List within a List

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

    public List<Users> users { get; set; }
}

public class Users
{
    public string name { get; set; }

    public string surname { get; set; }
}

List<Model> list = new List<Model>();

I need to select list where application = "applicationame" and users where surname = "surname" into one list.

like image 353
Reno Avatar asked Feb 02 '13 16:02

Reno


2 Answers

If you want to filter the models by applicationname and the remaining models by surname:

List<Model> 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<Model> newList = list
    .Where(m => m.application == "applicationname"
            &&  m.users.Any(u => u.surname == "surname"))
    .ToList();
like image 77
Tim Schmelter Avatar answered Sep 20 '22 15:09

Tim Schmelter


You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();
like image 32
Cédric Bignon Avatar answered Sep 22 '22 15:09

Cédric Bignon