Ticker

6/recent/ticker-posts

Standard Query Operators in LINQ

LINQ Standard Query Operators



LINQ (Language Integrated Query) provides a powerful and expressive way to query and manipulate data in .NET applications. The LINQ Standard Query Operators are a set of methods provided by the LINQ framework that enable you to perform common querying operations on data collections. These operators are defined as extension methods on the IEnumerable<T> and IQueryable<T> interfaces.

Here is a detailed explanation of some commonly used LINQ Standard Query Operators along with code examples:

  1. Where: Filters a sequence based on a specified condition and returns only the elements that satisfy the condition.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var evenNumbers = numbers.Where(n => n % 2 == 0); 
// Output: [2, 4]
  1. OfType: Filters the elements of a sequence based on a specified type and returns only the elements that are of that type.
csharp
var mixedList = new List<object> { 1, "two", 3, "four", 5 };
var integers = mixedList.OfType<int>(); 
// Output: [1, 3, 5]
  1. OrderBy: Sorts the elements of a sequence in ascending order based on a specified key.
csharp
var numbers = new List<int> { 5, 1, 4, 3, 2 }; var sortedNumbers = numbers.OrderBy(n => n); 
// Output: [1, 2, 3, 4, 5]
  1. ThenBy: Performs a secondary sort on the elements of a sequence that has already been sorted using OrderBy.
csharp
var products = new List<Product> { new Product { Name = "Keyboard", Price = 30 }, new Product { Name = "Mouse", Price = 20 }, new Product { Name = "Monitor", Price = 200 }, new Product { Name = "Speakers", Price = 50 }, }; 
var sortedProducts = products.OrderBy(p => p.Price).ThenBy(p => p.Name); // Output: [Mouse, Keyboard, Speakers, Monitor]
  1. GroupBy, ToLookup: Groups the elements of a sequence based on a specified key and returns a sequence of groups.
csharp
var students = new List<Student> { new Student { Name = "Alice", Grade = 90 }, new Student { Name = "Bob", Grade = 85 }, new Student { Name = "Charlie", Grade = 95 }, new Student { Name = "Alice", Grade = 80 }, }; 
var groupedStudents = students.GroupBy(s => s.Name); 
// Output: [{ Key = "Alice", [90, 80] }, { Key = "Bob", [85] }, { Key = "Charlie", [95] }]

The ToLookup operator works similarly to GroupBy but returns a lookup, which is a dictionary-like data structure.

  1. Join: Performs an inner join on two sequences based on a common key and returns a sequence of matched elements.
csharp
var customers = new List<Customer> { new Customer { Id = 1, Name = "Alice" }, new Customer { Id = 2, Name = "Bob" }, }; 
var orders = new List<Order> { new Order { Id = 1, Product = "Keyboard" }, new Order { Id = 2, Product = "Mouse" }, new Order { Id = 1, Product = "Monitor" }, }; 
var joinedData = customers.Join( orders, customer => customer.Id, order => order.Id, (customer, order) => new { CustomerName = customer.Name, OrderProduct = order.Product } ); 
// Output: [{ CustomerName = "Alice", OrderProduct = "Keyboard" }, // { CustomerName = "Alice", OrderProduct = "Monitor" }, // { CustomerName = "Bob", OrderProduct = "Mouse" }]
  1. GroupJoin: Performs a group join on two sequences based on a common key and returns a sequence of grouped elements.
csharp
var customers = new List<Customer> { new Customer { Id = 1, Name = "Alice" }, new Customer { Id = 2, Name = "Bob" }, }; 
var orders = new List<Order> { new Order { Id = 1, Product = "Keyboard" }, new Order { Id = 2, Product = "Mouse" }, new Order { Id = 1, Product = "Monitor" }, }; 
var groupedData = customers.GroupJoin( orders, customer => customer.Id, order => order.Id, (customer, orderGroup) => new { CustomerName = customer.Name, Orders = orderGroup } ); 
// Output: [{ CustomerName = "Alice", Orders = [{ Id = 1, Product = "Keyboard" }, // { Id = 1, Product = "Monitor" }] }, // { CustomerName = "Bob", Orders = [{ Id = 2, Product = "Mouse" }] }]
  1. Select: Projects each element of a sequence into a new form.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var squaredNumbers = numbers.Select(n => n * n); 
// Output: [1, 4, 9, 16, 25]
  1. All, Any: Checks if all or any element in a sequence satisfies a specified condition.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var allEven = numbers.All(n => n % 2 == 0); 
var anyOdd = numbers.Any(n => n % 2 != 0); 
// Output: allEven = false, anyOdd = true
  1. Contains: Determines whether a sequence contains a specified element.
csharp
var fruits = new List<string> { "apple", "banana", "orange" }; 
var containsBanana = fruits.Contains("banana"); 
// Output: containsBanana = true
  1. Aggregate: Applies an accumulator function over a sequence and returns the final result.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var sum = numbers.Aggregate((acc, n) => acc + n); 
// Output: sum = 15
  1. Average: Computes the average of a sequence of numeric values.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var average = numbers.Average(); 
// Output: average = 3
  1. Count: Counts the number of elements in a sequence.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var count = numbers.Count(); 
// Output: count = 5
  1. Max: Returns the maximum value in a sequence.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var max = numbers.Max(); // Output: max = 5
  1. Sum: Computes the sum of a sequence of numeric values.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var sum = numbers.Sum(); 
// Output: sum = 15
  1. ElementAt, ElementAtOrDefault: Returns the element at a specified index in a sequence.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var thirdElement = numbers.ElementAt(2); 
var tenthElementOrDefault = numbers.ElementAtOrDefault(9); 
// Output: thirdElement = 3, tenthElementOrDefault = 0 (default value for int)
  1. First, FirstOrDefault: Returns the first element of a sequence or the first element that satisfies a specified condition.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var firstEven = numbers.First(n => n % 2 == 0); 
var firstOrDefault = numbers.FirstOrDefault(); 
// Output: firstEven = 2, firstOrDefault = 1
  1. Last, LastOrDefault: Returns the last element of a sequence or the last element that satisfies a specified condition.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var lastOdd = numbers.Last(n => n % 2 != 0); 
var lastOrDefault = numbers.LastOrDefault(); 
// Output: lastOdd = 5, lastOrDefault = 5
  1. Single, SingleOrDefault: Returns the only element of a sequence or the only element that satisfies a specified condition. Throws an exception if there are no elements or more than one element.
csharp
var numbers = new List<int> { 1 }; 
var singleElement = numbers.Single(); 
var singleEven = numbers.Single(n => n % 2 == 0); 
// Output: singleElement = 1 (only element), singleEven = Exception (no element)
  1. SequenceEqual: Determines whether two sequences are equal by comparing their elements.
csharp
var numbers1 = new List<int> { 1, 2, 3 }; 
var numbers2 = new List<int> { 1, 2, 3 }; 
var numbers3 = new List<int> { 3, 2, 1 }; 
var areEqual = numbers1.SequenceEqual(numbers2); 
var areEqualIgnoringOrder = numbers1.SequenceEqual(numbers3); 
// Output: areEqual = true, areEqualIgnoringOrder = false
  1. Concat: Concatenates two sequences.
csharp
var numbers1 = new List<int> { 1, 2, 3 }; 
var numbers2 = new List<int> { 4, 5 }; 
var combinedNumbers = numbers1.Concat(numbers2); 
// Output: [1, 2, 3, 4, 5]
  1. DefaultIfEmpty: Returns a sequence with a default value if the source sequence is empty.
csharp
var numbers = new List<int>(); 
var numbersOrDefault = numbers.DefaultIfEmpty(); 
// Output: numbersOrDefault = [0] (default value for int)
  1. Empty, Range, Repeat: Generates sequences with specific characteristics.
csharp
var emptySequence = Enumerable.Empty<int>(); 
var rangeSequence = Enumerable.Range(1, 5); 
var repeatedValueSequence = Enumerable.Repeat("hello", 3); 
// Output: emptySequence = [], rangeSequence = [1, 2, 3, 4, 5], repeatedValueSequence = ["hello", "hello", "hello"]
  1. Distinct: Returns distinct elements from a sequence.
csharp
var numbers = new List<int> { 1, 2, 2, 3, 3, 3, 4, 5 }; 
var distinctNumbers = numbers.Distinct(); 
// Output: distinctNumbers = [1, 2, 3, 4, 5]
  1. Except: Returns the elements from one sequence that are not present in a second sequence.
csharp
var numbers1 = new List<int> { 1, 2, 3, 4, 5 }; 
var numbers2 = new List<int> { 4, 5, 6, 7 }; 
var numbersOnlyInFirst = numbers1.Except(numbers2); 
// Output: numbersOnlyInFirst = [1, 2, 3]
  1. Intersect: Returns the elements that are common to two sequences.
csharp
var numbers1 = new List<int> { 1, 2, 3, 4, 5 }; 
var numbers2 = new List<int> { 4, 5, 6, 7 }; 
var commonNumbers = numbers1.Intersect(numbers2); 
// Output: commonNumbers = [4, 5]
  1. Union: Returns the unique elements from two sequences.
csharp
var numbers1 = new List<int> { 1, 2, 3 }; 
var numbers2 = new List<int> { 3, 4, 5 }; 
var combinedNumbers = numbers1.Union(numbers2); 
// Output: combinedNumbers = [1, 2, 3, 4, 5]
  1. Skip, SkipWhile: Bypasses elements in a sequence based on a specified condition or number of elements.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var skippedNumbers = numbers.Skip(2); 
var skippedWhileEven = numbers.SkipWhile(n => n % 2 == 0); 
// Output: skippedNumbers = [3, 4, 5], skippedWhileEven = [1, 2, 3, 4, 5]
  1. Take, TakeWhile: Returns a specified number of elements from the start of a sequence or elements based on a specified condition.
csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var firstThreeNumbers = numbers.Take(3); 
var takenWhileLessThanFour = numbers.TakeWhile(n => n < 4); 
// Output: firstThreeNumbers = [1, 2, 3], takenWhileLessThanFour = [1, 2, 3]
  1. Conversion Operators: Convert a sequence to a different type or format.

Examples of conversion operators include ToList, ToDictionary, ToArray, ToLookup, ToHashSet, ToLookup, etc. These operators enable you to convert the query results into different collection types or data structures.

csharp
var numbers = new List<int> { 1, 2, 3, 4, 5 }; 
var listNumbers = numbers.ToList(); 
var dictionaryNumbers = numbers.ToDictionary(n => n); 
var arrayNumbers = numbers.ToArray(); 
// Output: listNumbers = [1, 2, 3, 4, 5], dictionaryNumbers = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5 }, // arrayNumbers = [1, 2, 3, 4, 5]

These are the LINQ standard query operators along with their code examples and explanations. You can use these operators to perform powerful data querying and manipulation operations on various collections in C#.

Post a Comment

0 Comments