Sperick
Sperick

Reputation: 2761

Filtering out null collection property using LINQ

I'm trying to extract a subset of a list based on a property. That property is itself a collection and I'm only interested in the values where this collection is not null

My code is:

var subGroupCollection = groupContext.SubGroups.Where(sg => sg.Holds != null).ToList();

I get the following run-time error:

Cannot compare elements of type 'System.Collections.Generic.ICollection`1[[WW2.Hold, WW2, Version=6.0.5848.30559, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported.

"Holds" is the name of the collection property(this is a HashSet of Hold objects)

What's the issue here and is there an obvious solution?

Upvotes: 2

Views: 260

Answers (1)

Servy
Servy

Reputation: 203802

The collection will never be null in EF. It might be empty, but it will never be null. In fact, you can't even compare the entire collection to null, which is exactly what the error is telling you. If you want to get items where that collection has any items, use Any to determine that.

Upvotes: 8

Related Questions