0

using LINQ how do I get this query to return all states except for the ones in the string array?

string[] states = { "FL", "CA", "IN", "AL", "MI" };
var headers = (from h in db.Headers
               where h.State != states.Any()
               select new
               {
                   description = h.Description,
                   state = h.State
               });
1
  • Christo's answer is correct, Selman's will work too. But just to expound a bit, you should look at the return values of the LINQ extensions. For example, Any() returns type bool, you are trying to compare a h.State (probably a string) to a bool. Commented May 20, 2014 at 15:26

2 Answers 2

5

You could try this:

 var headers = (from h in db.Headers
                where !states.Contains(h.State)
                select new
                {
                    description = h.Description,
                    state = h.State
                });
Sign up to request clarification or add additional context in comments.

3 Comments

I love and Hate you right now. Love you for answering this quickly and hate you for answering it so damn quickly, now I feel like a moron. LOL
@scripter78 you shouldn't feel like a moron. I suppose that you haven't used too much LINQ. If you had used a lot of LINQ, that would have been one of your first thoughts. You question is well formed and that you wanted is very clear, which both helped for your answer to be answered very quickly.
I knew it had something to do with Contains and did try that to begin with but how ever I had it which I can't recall at the moment, it would not work. and it was a lot more elaborate than your solution. That is the one thing I always go off of. If my solution gets too elaborate than I know I am doing something wrong. I do use Linq but I have never had to use it in the scenario here. Nonetheless thank you That saved me a ton of time and one hell of a headache
1

Probably you should use Contains because it will be translated as NOT IN into SQL however this is how you can do it with Any, it should be translated as NOT EXISTS:

var headers = (from h in db.Headers
               where !states.Any(x => x == h.State)
               select new
                   {
                       description = h.Description,
                       state = h.State
                   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.