Search code examples
c#linqenumerable

LINQ Enumerable in Enumerable - Why?


I have a Ticket class that contains a List of User objects:

class Ticket {
    public List<User> Users { get; set; }
}

I want to get all Users that are related to tickets. I do this:

var u = from t in db.Tickets
        where t.Users.Count() > 0
        select t.Users

That works but returns a Enumerable with 1 element. And that element is an Enumerable with the Users.

Why is it nested?


Solution

  • What you need to do is

      var u = (from t in db.Tickets from user in t.Users select user).ToList();
    

    Then you will have a flattened List of Users. There's no need to check for where t.Users.Count() > 0 and if you did need to you should be using where t.Users.Any() for efficiency.