Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does LINQ return when the results are empty

Tags:

c#

linq

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.

like image 402
David.Chu.ca Avatar asked Jul 28 '09 04:07

David.Chu.ca


People also ask

What does LINQ query return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

What is default if empty LINQ C#?

The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source.

Is null in LINQ C#?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.


1 Answers

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

like image 60
leppie Avatar answered Sep 18 '22 14:09

leppie