Skip to content

Latest commit

 

History

History
94 lines (87 loc) · 2.82 KB

File metadata and controls

94 lines (87 loc) · 2.82 KB

LINQ Basics

  • Select (Projection): Transforms each element in a collection.
    var uppercaseNames = names.Select(name => name.ToUpper());
  • Where (Filtering): Filters a sequence based on a predicate.
    var evenNumbers = numbers.Where(num => num % 2 == 0);
  • OrderBy / OrderByDescending (Sorting): Sorts elements in ascending or descending order.
    var sortedNames = names.OrderBy(name => name);
    var sortedNumbersDesc = numbers.OrderByDescending(num => num);

Element Operations

  • First / FirstOrDefault: Returns the first element, or a default value if the sequence is empty.
    var firstNumber = numbers.First();
    var firstOrDefault = numbers.FirstOrDefault();
  • Single / SingleOrDefault: Expects a single element and throws an exception if there is more than one.
    var singleNumber = numbers.Single();
    var singleOrDefault = numbers.SingleOrDefault();

Aggregation

  • Count: Counts the elements that satisfy a condition.
    var numberOfEvens = numbers.Count(num => num % 2 == 0);
  • Sum: Computes the sum of a sequence.
    var total = numbers.Sum();
  • Average: Computes the average of a sequence.
    var average = numbers.Average();

Set Operations

  • Distinct: Removes duplicate elements.
    var distinctNumbers = numbers.Distinct();
  • Union: Produces the set union of two sequences.
    var combinedNumbers = firstList.Union(secondList);
  • Intersect: Produces the set intersection of two sequences.
    var commonNumbers = firstList.Intersect(secondList);
  • Except: Produces the set difference of two sequences.
    var uniqueToFirstList = firstList.Except(secondList);

Conversion

  • ToArray: Converts a sequence to an array.
    var array = numbers.ToArray();
  • ToList: Converts a sequence to a list.
    var list = numbers.ToList();
  • ToDictionary: Converts a sequence to a dictionary.
    var dictionary = numbers.ToDictionary(num => num, num => num * num);

Quantifiers

  • Any: Checks if any elements satisfy a condition.
    var hasEvens = numbers.Any(num => num % 2 == 0);
  • All: Checks if all elements satisfy a condition.
    var allPositive = numbers.All(num => num > 0);

Generation

  • Range: Generates a sequence of numbers within a specified range.
    var range = Enumerable.Range(1, 10);
  • Repeat: Generates a sequence that contains one repeated value.
    var repeated = Enumerable.Repeat("Hello", 5);

This cheat sheet covers the essentials, but LINQ is a powerful tool with many more methods and nuances.