TheMixy
TheMixy

Reputation: 1296

Filter List of parent objects where List of child objects does not meet criteria

Let's say we have two classes (parent and child):

class Task
{
    public int IdTask 
    public string Task
    public List<User> ListUser 
    public bool Deleted
}

class User
{
    public int IdUser 
    public string Task
}

and then a big list of tasks List<Task>.

Now, I would like to find a filtered list of List<Task> where none of the users in ListUser have a certain IdUser (for example 99).

Currently I do it with a nested loop. Smth like this:

foreach (var item in tasks)
{
    var access = false;
    foreach (var t in item.ListUser)
    {
        if(t.IdUser == 99)
        {
            access = true;
        }
    }
    item.Deleted = access;
}
tasks.RemoveAll(x => x.Deleted);

Although the above works, it seems like an overkill. Can I acomplish the same, with a lambda expression (or linq)?

Upvotes: 0

Views: 193

Answers (2)

Chandu
Chandu

Reputation: 331

You can use below code

IEnumerable<Task> result=tasks.Where(task=> task.ListUser.Any(user=>user.IdUser == XXX))

Upvotes: 0

Hamed Naeemaei
Hamed Naeemaei

Reputation: 9638

You can use this code:

var newList = list.Where(e => !e.ListUser.Any(l => l.IdUser == 99));

which says, in effect, "create a new list with all the items except those that have a user list containing user 99".

Upvotes: 1

Related Questions