Shawn
Shawn

Reputation: 869

C# Linq Union Returning Null

I have a simple linq query that unionizes two tables that implement the same interface.

For this example, lets say IAnimal.

var q = (from d in db.Dogs
         where d.AnimalID = PetID
         select d.Name)
        .Union
        (from c in db.Cats
         where c.AnimalID = PetID
         select c.Name)

So if the dog portion has no members, q gets assigned {"", {whatever is in cat}}. Is there a way to remove that empty record without doing .Where(x=>x!="" | x!= String.Empty) after the query?

I know its not that big of a deal, but it seems like there should be a better way?

Upvotes: 1

Views: 2066

Answers (1)

tster
tster

Reputation: 18237

How is that not a good way? What is wrong with it?

Well.. there is one thing wrong with it. If should be:

.Where(x => !string.IsNullOrEmpty(x))

If you are using Entity Framework or some other LINQ provider which can't handle IsNullOrEMpty then the code should be:

.Where(x => x != null && x != "")

Your code using | instead of && and checks against the empty string twice but never null.

Upvotes: 2

Related Questions