DEV Community

Steve Mak
Steve Mak

Posted on

1

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

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay