Saturday, September 19, 2020

LINQ

  • LINQ stands for Language Integrated Query. LINQ gives to capability to query objects.
  • We can query, 
    • Objects in memory eg :Collections)(LINQ to Objects), 
    • Databases (LINQ to SQL), 
    • XML(LINQ to XML) 
    • ADO.NET Data Sets (LINQ to Data Sets). 
    •  class Book
          {
              public string Name { get; set; }
              public decimal Price { get; set; }
          }
      
      class BookRepository
          {
      
              public IEnumerable GetBooks()
              {
                  var boooks = new List()
                  {
                      new Book() { Name="Fundamentals of C#" , Price = 20 },
                      new Book() { Name="ASP.NET MVC" , Price = 30},
                      new Book() { Name="Entity Framework" , Price = 12 },
                      new Book() { Name ="Java" , Price = 10 },
                      new Book() { Name = "Web API" , Price = 15 },
                      new Book() { Name="Java Script Basics" , Price= 25 }
                  };
      
                  return boooks;
              }
          }
      
      class Program
          {
              static void Main(string[] args)
              {
                  var books = new BookRepository().GetBooks();
                  var cheapbooks = new List();
                  
                  if(books != null)
                  {
                      cheapbooks = books.Where(book=>book.Price >12).ToList();
                  }
      
                  foreach (var book in cheapbooks)
                  {
                      Console.WriteLine(book.Name);
                  }
      
                  Console.Read();
              }
          }
      
      
Some of the more frequently used standard query methods and keywords

Method/Keywords Syntax Description
Where
Where(Predicate) Filters a sequence of values based on a predicate.
OrderBy OrderBy(Predicate) Sorts the elements of a sequence in ascending order.
ThenBy ThenBy(Predicate) Performs a subsequent ordering of the elements in a sequence in ascending order.
Select Select(Predicate) Projects each element of a sequence into a new form.
Take Take(int) Returns a specified number of contiguous elements from the start of a collection/sequence.
Skip Skip(int) Bypasses a specified number of elements in a sequence and then returns the remaining elements.
FirstOrDefault FirstOrDefault(Predicate) Returns the first element of a sequence, or a default value if no element is found.
First First(Predicate) Returns the first element of a sequence.
Single Single(Predicate) Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.

No comments:

Post a Comment