0

I have a query that looks like this:

var TheQuery = (from t in MyDC.Table
                where....
                select new MyModel()
                {
                    Property1 = (int?)... ?? 0
                }

Sometimes, the where clause in the query returns no data to do the select. When this happens, MyModel is null. I was hoping that with the ?? 0 for every property the query would still return an object with Property1 set to 0.

How do I rewrite this so that when no data exists to fill MyModel, MyModel doesn't come back null?

2
  • can't you check the count. something like TheQuery.ToList().Count Commented Oct 15, 2012 at 21:09
  • Dont do that, use .Any() so that it doesnt have to actually count the entire list. Commented Oct 15, 2012 at 21:11

1 Answer 1

1

well if there is nothing to select, then no MyModel will be created. TheQuery will be an empty IEnumerable.

I'm not sure what is happening if you are getting a list of null objects. I'm not sure how that is possible.

You can check to see if there are results to your query like this:

var TheQuery =  from t in MyDC.Table
                where....
                select new MyModel()
                {
                    Property1 = (int?)... ?? 0
                }

var after = TheQuery.Any() ? 
            TheQuery : 
            Enumerable.Range(0, 1).Select(k => new MyModel() { Property1 = 0 });
Sign up to request clarification or add additional context in comments.

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.