1

here's my code. it works

var someField = "abc";

var list = Entities.Where(x=>SomeField).FirstOrDefault();

here's the problem, someField can also be null or string.empty. If someField is null or string.empty, I will select everything where SomeField is null or string.empty.

var list = Entities.Where(x=>SomeField  == null || SomeField == string.empty).FirstOrDefault();

right now, I have an if else statement to check if someField has value,then decided which query to use.

I need to combine the 2 queries into one. because if there are fields we need to check, then this if else statemetn will get very long.

1
  • In the first snippet you've implied that SomeField is of type bool. Now it's of type string? Your question is very unclear. Commented Oct 24, 2012 at 16:31

2 Answers 2

3

I suspect you actually want to match x.SomeField == someField, or everything if someField is null or empty, right?

I would do this:

var fetchAll = string.IsNullOrEmpty(someField);
var list = Entities.FirstOrDefault(x => fetchAll || x.SomeField == someField);

You can inline it, but I think the above is clearer than checking whether someField is null or empty within the query.

Note that I've used the overload of FirstOrDefault which takes a predicate - this is equivalent to using Where followed by FirstOrDefault, but a bit more concise.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, interesting. I suspect this is a more correct interpretation of the OP's intent.
1

I did a little sample, I'm just getting the entity with a null or empty value in SomeField...

I hope this works for you.

public class MyEntity
{
    public int ID { get; set; }

    public string SomeField { get; set; }
}

static void Main(string[] args)
{
   List<MyEntity> Entities = new List<MyEntity>();
   for (int i = 0; i < 10; i++)
   {
       Entities.Add(new MyEntity()
                   {
                       ID = i,
                       SomeField = "Value " + i.ToString()
                   });
   }

   Entities.Add(new MyEntity() { ID = 10, SomeField = null });
   var entity = Entities.Where(x => string.IsNullOrEmpty(x.SomeField)).FirstOrDefault();
}

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.