开发者

C# Linq Union Returning Null

开发者 https://www.devze.com 2023-01-20 12:36 出处:网络
I have a simple linq query that unionizes two tables that implement the same interface. For this example, lets say IAnimal.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消