DEV Community

Steve Mak
Steve Mak

Posted on

Cheatsheet for LINQ

Intro.

A query variable is always an enumerable type that will produce a sequence of elements when it is iterated over in a foreach statement or a direct call to its IEnumerator.MoveNext method.

Syntax

from .. in ..
[ join .. in .. on .. equals .. ]
[ where | orderby .. ascending | descending | let ]
[ group .. by .. into .. ]
select new {}
Enter fullscreen mode Exit fullscreen mode

Group clause

var queryCountryGroups =
    from country in countries
    group country by country.Name[0];
Enter fullscreen mode Exit fullscreen mode

Select clause

var queryNameAndPop =
    from country in countries
    select new { Name = country.Name, Pop = country.Population };
Enter fullscreen mode Exit fullscreen mode

Orderby clause

IEnumerable<Country> querySortedCountries =
    from country in countries
    orderby country.Area, country.Population descending
    select country;
Enter fullscreen mode Exit fullscreen mode

Join clause

var categoryQuery =
    from cat in categories
    join prod in products on cat equals prod.Category
    select new { Category = cat, Name = prod.Name };
Enter fullscreen mode Exit fullscreen mode

Let clause

string[] names = { "Svetlana Omelchenko", "Claire O'Donnell", "Sven Mortensen", "Cesar Garcia" };
IEnumerable<string> queryFirstNames =
    from name in names
    let firstName = name.Split(' ')[0]
    select firstName;

foreach (string s in queryFirstNames)
    Console.Write(s + " ");
//Output: Svetlana Claire Sven Cesar
Enter fullscreen mode Exit fullscreen mode

Subqueries in a query expression

var queryGroupMax =
    from student in students
    group student by student.GradeLevel into studentGroup
    select new
    {
        Level = studentGroup.Key,
        HighestScore =
            (from student2 in studentGroup
             select student2.Scores.Average())
             .Max()
    };

// percentileQuery is an IEnumerable<IGrouping<int, Country>>
var percentileQuery =
    from country in countries
    let percentile = (int) country.Population / 10_000_000
    group country by percentile into countryGroup
    where countryGroup.Key >= 20
    orderby countryGroup.Key
    select countryGroup;

// grouping is an IGrouping<int, Country>
foreach (var grouping in percentileQuery)
{
    Console.WriteLine(grouping.Key);
    foreach (var country in grouping)
        Console.WriteLine(country.Name + ":" + country.Population);
}
Enter fullscreen mode Exit fullscreen mode

Standard query operators

Ref: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?view=netcore-3.1

Where Select SelectMany Skip SkipWhile
Take TakeWhile Join GroupJoin Concate
OrderBy OrderByDescending ThenBy ThenByDescending Reverse
GroupBy Distinct Union Intersect Except
AsEnumerable AsQueryable ToArray ToList ToDictionary
ToLookup OfType Cast SequenceEqual First
FirstOrDefault Last LastOrDefault Single SingleOfDefault
ElementAt ElementAtOrDefault DefaultEmpty All Any
Contains Count LongCout Sum Min
Max Average Aggregate equal/Equals from/From
in/In into/Into key let Group
Range Repeat
Enter fullscreen mode Exit fullscreen mode

Top comments (0)