What does LINQ return when the results are empty
I have a question about LINQ query. Normally a query returns a IEnumerable 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.
It will return an empty enumerable. It wont be null. You can sleep sound :)
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
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(转储来自LinqPad)
链接地址: http://www.djcxy.com/p/53708.html上一篇: IEnumerable和递归使用yield return
下一篇: 当结果为空时,LINQ会返回什么结果?