tags:

views:

34

answers:

1

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?

A: 

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.

tster
Its unionizing nothing with something and then scanning the something to pick out the nothing. Its seems like it would be better to determine that there is nothing, and then just return the other side of the union. Perhaps this gets worked out in the SQL generation though. Its not that big of a deal like I said, it just seems like there should be a way to do the check then union instead of doing a union and then a check.
Shawn
How do you know what LINQ is doing? Linq might very well not enumerate your objects until later at which point it can discard the first set anyways. Plus, doing a union is essentially free. It just enumerates the first set, then enumerates the second set. It's **not** like concatenating strings.
tster
And just an fyi, string.IsNullOrEmpty() doesn't have a translation to Sql. I know I didn't specify that though.
Shawn
@Shawn, you still need to change your code there. see update.
tster
Yeah, my code was bad. It was more or less a typo. I always thought that String.Empty and "" were different, but they aren't. I also thought that strings couldn't have null values but again I was wrong. Thanks.
Shawn
I just looked at the SQL generated and it essentially does a union and then a where. I know where are usually highly optimized in the db, but it still seems like it does it in the wrong order.
Shawn
@Shawn, you are worrying about the wrong thing. My recommendation is to write the cleanest code possible and then when you run into performance issues change the code to make it faster. And don't get bogged down worrying to much about the SQL generted by your ORM. Entity Framework know how to make fast queries.
tster
Alright fair enough. Thanks for the help.
Shawn