Coder Perfect

When the results of a query are returned using LINQ, what do you get?

Problem

I’d want to ask you a question about LINQ queries. A query usually returns an IEnumerableT> type. I’m not sure if the result is null or not if it’s empty. If nothing is discovered in the IEnumerable result, I’m not sure if ToList() will throw an error or just return an empty Liststring>.

   List<string> list = {"a"};
   // is the result null or something else?
   IEnumerable<string> ilist = from x in list where x == "ABC" select x;
   // Or directly to a list, exception thrown?
   List<string> list1 = (from x in list where x == "ABC" select x).ToList();

I realize it’s an easy question, but I don’t have Visual Studio installed at the moment.

Asked by David.Chu.ca

Solution #1

It will give you an empty enumerable as a result. It isn’t going to be null. You may rest easy:)

Answered by leppie

Solution #2

You can also take a look at the.Any() method.

if (!YourResult.Any())

Just a reminder that Performing a.FirstOrDefault()/ will still fetch the records from the database. You’ll incur the same overhead with Where(), but you’ll be able to catch the object(s) returned from the query.

Answered by Noich

Solution #3

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

(This is a LinqPad dump)

Answered by JP Alioto

Solution #4

.ToList returns a list that is empty. (Identical to new ListT>());

Answered by Paul van Brenk

Solution #5

If you try to get the first element on a query that returns no results in Linq-to-SQL, you’ll get the sequence has no elements error. I can guarantee you that the error you’ve encountered is not the same as an object reference that hasn’t been set to an instance of the object. No, it won’t return null because null can’t say a sequence has no elements; instead, it will always say object reference not set to an instance of an object.

Answered by kay.one

Post is based on https://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty