What does LINQ return when the results are empty in C#?

CsharpServer Side ProgrammingProgramming

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language.

You can write LINQ queries in C# for SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface.

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

ToList returns an empty list

Example

class Program{
   public static void Main(){
      List<string> list = new List<string> { "a" };
      IEnumerable<string> ilist = list.Where(x => x == "ABC").ToList();
      System.Console.WriteLine(ilist.Count());
      foreach (var item in ilist){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}

Output

0

Example

class Program{
   public static void Main(){
      List<int> list = new List<int> { 1 };
      IEnumerable<int> ilist = list.Where(x => x == 3).ToList();
      System.Console.WriteLine(ilist.Count());
      foreach (var item in ilist){
         System.Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}

Output

0
raja
Published on 25-Sep-2020 14:42:48
Advertisements