What does LINQ return when the results are empty

C#Linq

C# Problem Overview


I have a question about LINQ query. Normally a query returns a IEnumerable<T> type. If the return is empty, not sure if it is null or not. I am not sure if the following ToList() will throw an exception or just a empty List<string> if nothing found in IEnumerable result?

   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 know it is a very simple question, but I don't have VS available for the time being.

C# Solutions


Solution 1 - C#

It will return an empty enumerable. It won't be null. You can sleep sound :)

Solution 2 - C#

You can also check the .Any() method:

if (!YourResult.Any())

Just a note that .Any will still retrieve the records from the database; doing a .FirstOrDefault()/.Where() will be just as much overhead but you would then be able to catch the object(s) returned from the query

Solution 3 - C#

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

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

(Dump is from LinqPad)

Solution 4 - C#

.ToList returns an empty list. (same as new List<T>() );

Solution 5 - C#

In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object. in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;)

Solution 6 - C#

Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.

Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.

Solution 7 - C#

It won't throw exception, you'll get an empty list.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid.Chu.caView Question on Stackoverflow
Solution 1 - C#leppieView Answer on Stackoverflow
Solution 2 - C#NoichView Answer on Stackoverflow
Solution 3 - C#JP AliotoView Answer on Stackoverflow
Solution 4 - C#Paul van BrenkView Answer on Stackoverflow
Solution 5 - C#kay.oneView Answer on Stackoverflow
Solution 6 - C#SpenceView Answer on Stackoverflow
Solution 7 - C#Jimmy ChandraView Answer on Stackoverflow