New LINQ operators in .NET 6-10
suggest changeFor about ten years the set of LINQ operators barely changed. Starting with .NET 6, almost every release has added operators for things people used to write by hand with GroupBy, OrderBy or Aggregate, or copy from Stack Overflow and helper libraries like MoreLINQ.
| Release | New operators |
|---|---|
| .NET 6 | Chunk, MinBy/MaxBy, DistinctBy/UnionBy/IntersectBy/ExceptBy, Take(Range), TryGetNonEnumeratedCount, FirstOrDefault(defaultValue), three-way Zip |
| .NET 7 | Order/OrderDescending |
| .NET 8 | ToDictionary() for key/value pairs and tuples |
| .NET 9 | CountBy, AggregateBy, Index |
| .NET 10 | LeftJoin/RightJoin, Shuffle, Sequence/InfiniteSequence |
All of them are ordinary extension methods in System.Linq.Enumerable, so you only need a project that targets the right .NET version. No new C# syntax is involved.
Each section below shows the new operator next to the code it replaces. The examples are .NET 10 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.
Chunk: split a sequence into batches (.NET 6)
Chunk(size) splits a sequence into arrays of at most size elements. The last chunk holds whatever is left over:
int[] ids = [101, 102, 103, 104, 105, 106, 107];
foreach (int[] batch in ids.Chunk(3))
{
Console.WriteLine($"sending batch: {string.Join(", ", batch)}");
}
sending batch: 101, 102, 103
sending batch: 104, 105, 106
sending batch: 107
This is what you want when an API accepts at most N items per call, or when you insert rows into a database in batches.
Before .NET 6 the usual LINQ-only trick was to group by index divided by batch size:
var batches = ids
.Select((id, i) => (id, i))
.GroupBy(x => x.i / 3, x => x.id)
.Select(g => g.ToArray());
It works but it's hard to read, and GroupBy reads the whole source before returning the first group. Chunk is lazy: it produces each array as soon as it has size elements, so it also works on huge or never-ending sequences. Each chunk is a new array that you can keep or change.
Build your own LINQ operators for IEnumerableBatch operator like this yourself. On .NET 6 and later you can use Chunk instead.
MinBy and MaxBy: the element with the smallest or largest key (.NET 6)
Min and Max with a selector return the smallest or largest key. Usually you want the element that has it:
Product[] products =
[
new("Keyboard", 49.99m, 12),
new("Mouse", 19.99m, 40),
new("Monitor", 189.00m, 3),
new("Cable", 4.99m, 40),
];
// before .NET 6
Product cheapestOld = products.OrderBy(p => p.Price).First();
Product cheapestAgg = products.Aggregate((a, b) => b.Price < a.Price ? b : a);
// .NET 6
Product cheapest = products.MinBy(p => p.Price)!;
Product priciest = products.MaxBy(p => p.Price)!;
Console.WriteLine($"cheapest: {cheapest.Name}, priciest: {priciest.Name}");
// Max returns the key, MaxBy returns the element
Console.WriteLine(products.Max(p => p.Stock));
Console.WriteLine(products.MaxBy(p => p.Stock));
// empty sequence of reference type: null; of value type: throws
Product[] none = [];
Console.WriteLine(none.MinBy(p => p.Price) is null);
int[] noInts = [];
try { noInts.MinBy(x => x); }
catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
record Product(string Name, decimal Price, int Stock);
cheapest: Cable, priciest: Monitor
40
Product { Name = Mouse, Price = 19.99, Stock = 40 }
True
Sequence contains no elements
Things to know:
OrderBy(...).First()sorts the whole sequence (O(n log n)) just to read one element.MinByis a single O(n) pass.- On a tie
MinBy/MaxByreturn the first matching element: Mouse and Cable both have 40 in stock, and Mouse comes first. - On an empty sequence they behave like
Min/Max: they returnnullwhen the element type is a reference type (hence the!above), and throwInvalidOperationExceptionfor value types. - Both have an overload that takes an
IComparer<TKey>.
DistinctBy, UnionBy, IntersectBy, ExceptBy (.NET 6)
The classic set operators Distinct, Union, Intersect and Except compare whole elements. To compare by a property you had to write an IEqualityComparer<T> (see Distinct and Except). The ...By versions take a key selector instead:
User[] signups =
[
new(1, "ana@example.com", "Ana"),
new(2, "bob@example.com", "Bob"),
new(3, "ANA@example.com", "Ana B."),
new(4, "cy@example.com", "Cy"),
];
User[] banned = [new(9, "bob@example.com", "Robert")];
// before .NET 6: GroupBy + First
var oldUnique = signups.GroupBy(u => u.Email.ToLowerInvariant()).Select(g => g.First());
// DistinctBy keeps the first element for each key
var unique = signups.DistinctBy(u => u.Email, StringComparer.OrdinalIgnoreCase);
Print("DistinctBy", unique);
// ExceptBy: second sequence is a sequence of KEYS, not of elements
var allowed = signups.ExceptBy(banned.Select(b => b.Email), u => u.Email);
Print("ExceptBy", allowed);
// IntersectBy: also keys
string[] vipEmails = ["cy@example.com", "ana@example.com"];
Print("IntersectBy", signups.IntersectBy(vipEmails, u => u.Email));
// UnionBy: both sequences of elements
Print("UnionBy", signups.UnionBy(banned, u => u.Email));
static void Print(string label, IEnumerable<User> users) =>
Console.WriteLine($"{label,-12}: {string.Join(", ", users.Select(u => $"{u.Id}:{u.Name}"))}");
record User(int Id, string Email, string Name);
DistinctBy : 1:Ana, 2:Bob, 4:Cy
ExceptBy : 1:Ana, 3:Ana B., 4:Cy
IntersectBy : 1:Ana, 4:Cy
UnionBy : 1:Ana, 2:Bob, 3:Ana B., 4:Cy
Notes:
- The optional last argument is an
IEqualityComparer<TKey>for the key. HereStringComparer.OrdinalIgnoreCasemakesana@andANA@the same user. That's much shorter than writing a comparer class forUser. - When several elements share a key, the first one wins and the original order is kept.
ExceptByandIntersectBytake the second sequence as keys (IEnumerable<TKey>), not as elements. That's handy: you can pass a list of ids or emails without building fakeUserobjects. If you have elements, project them:banned.Select(b => b.Email).UnionBytakes elements for both sequences, since its result contains elements from both.- Like the classic versions, these are set operations: the result has no duplicate keys.
[1, 1, 2, 3, 3].ExceptBy([2], x => x)returns1, 3, not1, 1, 3, 3.
Take with a range (.NET 6)
Take accepts a C# Range, so you can slice any IEnumerable<T> with the same .. and ^ syntax you use on arrays and strings:
IEnumerable<int> log = Enumerable.Range(1, 10);
Show("Take(..3)", log.Take(..3)); // first 3 == Take(3)
Show("Take(^3..)", log.Take(^3..)); // last 3 == TakeLast(3)
Show("Take(2..5)", log.Take(2..5)); // items 2,3,4 == Skip(2).Take(3)
Show("Take(2..^2)", log.Take(2..^2)); // drop 2 at each end == Skip(2).SkipLast(2)
Show("Take(^4..^1)", log.Take(^4..^1));
// ElementAt with ^ index (.NET 6)
Console.WriteLine($"ElementAt(^1): {log.ElementAt(^1)}");
// out-of-range is clamped, never throws
Show("Take(5..100)", log.Take(5..100));
static void Show(string label, IEnumerable<int> xs) =>
Console.WriteLine($"{label,-13}: {string.Join(" ", xs)}");
Take(..3) : 1 2 3
Take(^3..) : 8 9 10
Take(2..5) : 3 4 5
Take(2..^2) : 3 4 5 6 7 8
Take(^4..^1) : 7 8 9
ElementAt(^1): 10
Take(5..100) : 6 7 8 9 10
Indexes count from 0 and the end of the range is exclusive, as everywhere else in C#. Indexes from the end (^n) only work if LINQ knows where the end is, so for a lazy sequence it has to buffer the last n elements. Unlike array slicing, a range that goes past the end isn't an error: Take just returns fewer items, like plain Take(n) does. See Skip and Take for the classic overloads and paging.
.NET 6 also added ElementAt(Index) and ElementAtOrDefault(Index), so log.ElementAt(^1) gets the last element.
TryGetNonEnumeratedCount (.NET 6)
Count() on an arbitrary IEnumerable<T> might have to walk the whole sequence, and if the sequence is a database query or a one-shot iterator, that walk runs the query or uses up the data. TryGetNonEnumeratedCount returns the count only if it's available cheaply, without enumerating:
#:property PublishAot=false
Report("List<int>", new List<int> { 1, 2, 3 });
Report("int[] + Select", new[] { 1, 2, 3 }.Select(x => x * 2));
Report("Where", new[] { 1, 2, 3 }.Where(x => x > 1));
Report("iterator", Numbers());
static void Report(string label, IEnumerable<int> source)
{
if (source.TryGetNonEnumeratedCount(out int count))
Console.WriteLine($"{label,-15}: {count} (no enumeration)");
else
Console.WriteLine($"{label,-15}: unknown without enumerating");
}
static IEnumerable<int> Numbers() { yield return 1; yield return 2; }
List<int> : 3 (no enumeration)
int[] + Select : 3 (no enumeration)
Where : unknown without enumerating
iterator : unknown without enumerating
It succeeds for collections (ICollection<T>, arrays) and for some LINQ results whose size is known up front, like Select over an array. It can't know how many items pass a Where filter or how many a yield return method will produce. Use it to pre-size a buffer when you can, and fall back to growing one when you can't:
var list = source.TryGetNonEnumeratedCount(out int n) ? new List<T>(n) : new List<T>();
The #:property PublishAot=false line matters for this example. File-based apps default to Native AOT, and AOT builds use a smaller LINQ implementation that skips some of these shortcuts, so without that line int[] + Select prints "unknown". In a normal .csproj project you get the output shown above. Treat a false result as "don't know", never as "empty".
Other small .NET 6 additions
FirstOrDefault, LastOrDefault and SingleOrDefault accept the default value to return when nothing matches, and Zip can combine three sequences into a tuple:
int[] empty = [];
Console.WriteLine(empty.FirstOrDefault(-1));
Console.WriteLine(empty.SingleOrDefault(x => x > 5, -1));
string[] names = ["Ana", "Bob", "Cy"];
int[] ages = [31, 25, 40];
string[] cities = ["Oslo", "Rome", "Lima"];
foreach (var (name, age, city) in names.Zip(ages, cities))
Console.WriteLine($"{name} {age} {city}");
-1
-1
Ana 31 Oslo
Bob 25 Rome
Cy 40 Lima
Without the default argument, FirstOrDefault on an empty int[] returns 0, and you can't tell "no element" from "the element was 0". Min and Max also gained overloads that take an IComparer<T>.
Order and OrderDescending (.NET 7)
To sort elements by themselves you used to write the identity lambda x => x. Order() and OrderDescending() say that directly:
int[] scores = [72, 95, 64, 88];
string[] tags = ["beta", "Zed", "alpha", "Alpha"];
Console.WriteLine(string.Join(" ", scores.OrderBy(x => x))); // before .NET 7
Console.WriteLine(string.Join(" ", scores.Order())); // .NET 7
Console.WriteLine(string.Join(" ", scores.OrderDescending()));
Console.WriteLine(string.Join(" ", tags.Order())); // culture-aware default
Console.WriteLine(string.Join(" ", tags.Order(StringComparer.Ordinal))); // by char code
64 72 88 95
64 72 88 95
95 88 72 64
alpha Alpha beta Zed
Alpha Zed alpha beta
They return IOrderedEnumerable<T>, so ThenBy still works after them, and they take an optional IComparer<T>. Strings sort with the current culture by default; pass StringComparer.Ordinal when you need results that don't depend on the machine's culture. Like OrderBy, the sort is stable. See Query Ordering for OrderBy and ThenBy.
CountBy: how many per key (.NET 9)
Counting items per key is one of the most common uses of GroupBy. CountBy does it directly and returns KeyValuePair<TKey, int> items:
Order[] orders =
[
new("ana", "books", 12.50m),
new("bob", "games", 59.99m),
new("ana", "games", 19.99m),
new("cy", "books", 8.00m),
new("ana", "books", 30.00m),
];
// before .NET 9
foreach (var g in orders.GroupBy(o => o.Customer))
Console.WriteLine($"{g.Key}: {g.Count()}");
// .NET 9: CountBy returns IEnumerable<KeyValuePair<TKey, int>>
foreach (var (customer, count) in orders.CountBy(o => o.Customer))
Console.WriteLine($"{customer}: {count}");
// most common category
var top = orders.CountBy(o => o.Category).MaxBy(kv => kv.Value);
Console.WriteLine($"top category: {top.Key} ({top.Value} orders)");
// handy with ToDictionary() (.NET 8 overload for KeyValuePair)
Dictionary<string, int> perCategory = orders.CountBy(o => o.Category).ToDictionary();
Console.WriteLine(perCategory["books"]);
record Order(string Customer, string Category, decimal Total);
ana: 3
bob: 1
cy: 1
ana: 3
bob: 1
cy: 1
top category: books (3 orders)
3
The results are the same, but GroupBy stores every element of every group just so you can count them. CountBy keeps only a counter per key. Keys come out in the order they were first seen, and an optional IEqualityComparer<TKey> controls how keys are compared.
The parameterless ToDictionary() used above was added in .NET 8. It works on any sequence of KeyValuePair<TKey, TValue> or (TKey, TValue) tuples, so you no longer write .ToDictionary(kv => kv.Key, kv => kv.Value).
AggregateBy: any per-key aggregation (.NET 9)
AggregateBy is the general form of CountBy: for each key it starts from a seed and folds the elements into it, like Aggregate does for a whole sequence:
Order[] orders =
[
new("ana", "books", 12.50m),
new("bob", "games", 59.99m),
new("ana", "games", 19.99m),
new("cy", "books", 8.00m),
new("ana", "books", 30.00m),
];
// before .NET 9
foreach (var g in orders.GroupBy(o => o.Customer))
Console.WriteLine($"{g.Key}: {g.Sum(o => o.Total)}");
// .NET 9: seed + accumulator per key
foreach (var (customer, total) in orders.AggregateBy(
keySelector: o => o.Customer,
seed: 0m,
func: (sum, o) => sum + o.Total))
{
Console.WriteLine($"{customer}: {total}");
}
// seed can depend on the key; accumulate into any type
var categoriesPerCustomer = orders.AggregateBy(
o => o.Customer,
seedSelector: customer => new SortedSet<string>(),
(set, o) => { set.Add(o.Category); return set; });
foreach (var (customer, set) in categoriesPerCustomer)
Console.WriteLine($"{customer}: {string.Join(", ", set)}");
// min and max per key in one pass
var range = orders.AggregateBy(
o => o.Category,
seed: (Min: decimal.MaxValue, Max: decimal.MinValue),
(acc, o) => (Math.Min(acc.Min, o.Total), Math.Max(acc.Max, o.Total)));
foreach (var (category, (min, max)) in range)
Console.WriteLine($"{category}: {min} - {max}");
record Order(string Customer, string Category, decimal Total);
ana: 62.49
bob: 59.99
cy: 8.00
ana: 62.49
bob: 59.99
cy: 8.00
ana: books, games
bob: games
cy: books
books: 8.00 - 30.00
games: 19.99 - 59.99
There are two overloads: one takes a seed value, the other a seedSelector function that gets the key and returns the seed for that key.
Gotcha: a mutable seed passed as a value is a single object shared by every key. Use seedSelector when the accumulator is a collection:
(string Key, int N)[] items = [("a", 1), ("b", 2), ("a", 3)];
// wrong: one List instance is the seed for every key
var wrong = items.AggregateBy(x => x.Key, seed: new List<int>(), (list, x) => { list.Add(x.N); return list; });
foreach (var (k, list) in wrong) Console.WriteLine($"{k}: [{string.Join(", ", list)}]");
// right: seedSelector creates a new List per key
var right = items.AggregateBy(x => x.Key, seedSelector: _ => new List<int>(), (list, x) => { list.Add(x.N); return list; });
foreach (var (k, list) in right) Console.WriteLine($"{k}: [{string.Join(", ", list)}]");
a: [1, 2, 3]
b: [1, 2, 3]
a: [1, 3]
b: [2]
If what you really want is a list of elements per key, that's just GroupBy or ToLookup. Use AggregateBy when the per-key result is smaller than the group: a sum, a min/max pair, a set of distinct values.
Index: elements with their position (.NET 9)
Select((item, index) => ...) has been the way to get an element's position since .NET 3.5. Index() returns (int Index, T Item) tuples, which you can deconstruct directly in foreach:
string[] podium = ["Ana", "Bob", "Cy"];
// before .NET 9
foreach (var (name, i) in podium.Select((name, i) => (name, i)))
Console.WriteLine($"{i + 1}. {name}");
// .NET 9: Index() yields (int Index, T Item)
foreach (var (i, name) in podium.Index())
Console.WriteLine($"{i + 1}. {name}");
// the tuple elements are named Index and Item
var firstC = podium.Index().First(x => x.Item.StartsWith('C'));
Console.WriteLine($"{firstC.Item} at {firstC.Index}");
1. Ana
2. Bob
3. Cy
1. Ana
2. Bob
3. Cy
Cy at 2
Note the order: the index comes first, the item second. That's the opposite of the Select overload's lambda parameters.
LeftJoin and RightJoin (.NET 10)
LINQ has always had Join, which is an SQL inner join: elements without a match on the other side are dropped. A left outer join required the GroupJoin + SelectMany + DefaultIfEmpty pattern that few people can write from memory. .NET 10 adds LeftJoin and RightJoin:
Customer[] customers = [new(1, "Ana"), new(2, "Bob"), new(3, "Cy")];
Order[] orders = [new(10, 1, 25m), new(11, 1, 40m), new(12, 3, 15m), new(13, 7, 99m)];
// before .NET 10: GroupJoin + SelectMany + DefaultIfEmpty
var oldLeft = customers
.GroupJoin(orders, c => c.Id, o => o.CustomerId, (c, os) => new { c, os })
.SelectMany(x => x.os.DefaultIfEmpty(), (x, o) => new { x.c.Name, OrderId = o?.Id });
// or in query syntax
var oldLeftQuery =
from c in customers
join o in orders on c.Id equals o.CustomerId into os
from o in os.DefaultIfEmpty()
select new { c.Name, OrderId = o?.Id };
Console.WriteLine("old LEFT JOIN:");
foreach (var row in oldLeft) Console.WriteLine($" {row.Name,-4} {row.OrderId?.ToString() ?? "-"}");
// .NET 10
Console.WriteLine("LeftJoin:");
var left = customers.LeftJoin(orders,
c => c.Id,
o => o.CustomerId,
(c, o) => new { c.Name, OrderId = o?.Id, Total = o?.Total });
foreach (var row in left)
Console.WriteLine($" {row.Name,-4} {row.OrderId?.ToString() ?? "-",-3} {row.Total?.ToString() ?? "-"}");
Console.WriteLine("RightJoin:");
var right = customers.RightJoin(orders,
c => c.Id,
o => o.CustomerId,
(c, o) => $"order {o.Id}: {c?.Name ?? "(unknown customer)"}");
foreach (var row in right) Console.WriteLine($" {row}");
record Customer(int Id, string Name);
record Order(int Id, int CustomerId, decimal Total);
old LEFT JOIN:
Ana 10
Ana 11
Bob -
Cy 12
LeftJoin:
Ana 10 25
Ana 11 40
Bob - -
Cy 12 15
RightJoin:
order 10: Ana
order 11: Ana
order 12: Cy
order 13: (unknown customer)
LeftJoinkeeps every element of the first (outer) sequence. When there's no match, the result selector getsdefaultfor the inner element: Bob has no orders, sooisnull.RightJoinkeeps every element of the second sequence. Order 13 points to customer 7, which doesn't exist, socisnull.- The parameters are the same as
Join's: inner sequence, outer key, inner key, result selector, and an optionalIEqualityComparer<TKey>. - There's no query-syntax keyword for them (no
left joinin C# 14), so in query syntax you still use theinto+DefaultIfEmptypattern. System.Linq.Queryablehas them too, and EF Core 10 translates them to SQLLEFT JOIN/RIGHT JOIN.
Watch out with value types. The missing side is default(T), which for a struct or tuple is a "zero" value, not null:
string[] days = ["Mon", "Tue", "Wed"];
(string Day, int Sales)[] sales = [("Mon", 5), ("Wed", 0)];
foreach (var row in days.LeftJoin(sales, d => d, s => s.Day, (d, s) => $"{d}: {s.Sales} (Day={s.Day ?? "null"})"))
Console.WriteLine(row);
Mon: 5 (Day=Mon)
Tue: 0 (Day=null)
Wed: 0 (Day=Wed)
Tuesday (no row) and Wednesday (a real row with 0 sales) both show 0 sales. To tell them apart, check a field that can't be empty in a real row (here s.Day), or use a class or a nullable struct for the inner sequence.
See JOINS and Joining multiple sequences for inner joins and GroupJoin.
Shuffle (.NET 10)
Shuffle() returns the elements in random order:
string[] deck = ["A", "K", "Q", "J", "10", "9"];
Console.WriteLine(string.Join(" ", deck.Shuffle()));
Console.WriteLine(string.Join(" ", deck.Shuffle()));
Console.WriteLine(string.Join(" ", deck)); // source untouched
// pick 3 random distinct items
Console.WriteLine(string.Join(" ", deck.Shuffle().Take(3)));
// before .NET 10
Console.WriteLine(string.Join(" ", deck.OrderBy(_ => Random.Shared.Next())));
string[] copy = [.. deck];
Random.Shared.Shuffle(copy); // .NET 8, in place
Console.WriteLine(string.Join(" ", copy));
// lazy: a new order every enumeration
var shuffled = deck.Shuffle();
Console.WriteLine(string.Join(" ", shuffled));
Console.WriteLine(string.Join(" ", shuffled));
K 10 A Q 9 J
J A 9 10 Q K
A K Q J 10 9
10 J A
10 9 J A Q K
10 9 K Q J A
J 9 Q K 10 A
Q 10 A K 9 J
(Your output will differ, that's the point.)
- The source isn't changed.
Random.Shared.Shuffle(array)(.NET 8) shuffles an array or span in place, which avoids allocating a copy. OrderBy(_ => Random.Shared.Next())works, but it sorts the whole sequence, and the more commonOrderBy(_ => Guid.NewGuid())is slower still.Shuffledoes a Fisher-Yates shuffle.- Like other LINQ operators,
Shuffle()is lazy. Each enumeration of the sameshuffledvariable produces a new random order. CallToArray()once if you need a stable shuffled order, for example to show a quiz and then check the answers. - It uses a shared random generator, so you can't seed it for repeatable tests. When you need repeatable shuffles, copy to an array and call
Shuffleon your ownnew Random(seed).
Sequence and InfiniteSequence (.NET 10)
Enumerable.Range(start, count) only counts up by 1 and only for int. .NET 10 adds Enumerable.Sequence(start, endInclusive, step) and Enumerable.InfiniteSequence(start, step), which work for any numeric type:
Console.WriteLine(string.Join(" ", Enumerable.Sequence(0, 20, 5)));
Console.WriteLine(string.Join(" ", Enumerable.Sequence(10, 0, -3)));
Console.WriteLine(string.Join(" ", Enumerable.Sequence(0.0, 1.0, 0.25)));
Console.WriteLine(string.Join(" ", Enumerable.InfiniteSequence(1, 2).Take(5)));
Console.WriteLine(string.Join(" ", Enumerable.Sequence(1L, 3L, 1L)));
0 5 10 15 20
10 7 4 1
0 0.25 0.5 0.75 1
1 3 5 7 9
1 2 3
Unlike Range, the second argument of Sequence is the inclusive end, not a count. A negative step counts down. InfiniteSequence never ends, so always limit it with Take or TakeWhile. See Range and Repeat for the older generators.
Async streams and IQueryable
In .NET 10 the same operators are also available for async streams through System.Linq.AsyncEnumerable: Chunk, DistinctBy, CountBy, AggregateBy, Index, LeftJoin, Shuffle and the rest, with an Async suffix on the ones that return a single value (MinByAsync, MaxByAsync). See Async streams: IAsyncEnumerable and await foreach.
System.Linq.Queryable got matching methods for IQueryable<T>, but whether a query provider can translate a given operator to SQL is up to the provider. EF Core 10 translates LeftJoin and RightJoin, but many of the other new operators aren't translated. If a provider can't translate an operator, the query fails at runtime, so check your provider's documentation.
Quick reference
| You used to write | Now write | Since |
|---|---|---|
Select((x, i) => ...).GroupBy(t => t.i / n) |
Chunk(n) |
.NET 6 |
OrderBy(x => x.Price).First() |
MinBy(x => x.Price) |
.NET 6 |
GroupBy(x => x.Key).Select(g => g.First()) |
DistinctBy(x => x.Key) |
.NET 6 |
Except(other, new KeyComparer()) |
ExceptBy(otherKeys, x => x.Key) |
.NET 6 |
Skip(2).Take(3) / TakeLast(3) |
Take(2..5) / Take(^3..) |
.NET 6 |
FirstOrDefault() ?? fallback (and the 0 problem) |
FirstOrDefault(fallback) |
.NET 6 |
OrderBy(x => x) |
Order() |
.NET 7 |
ToDictionary(kv => kv.Key, kv => kv.Value) |
ToDictionary() |
.NET 8 |
GroupBy(k).Select(g => (g.Key, g.Count())) |
CountBy(k) |
.NET 9 |
GroupBy(k).Select(g => (g.Key, g.Sum(...))) |
AggregateBy(k, seed, func) |
.NET 9 |
Select((x, i) => (x, i)) |
Index() |
.NET 9 |
GroupJoin + SelectMany + DefaultIfEmpty |
LeftJoin / RightJoin |
.NET 10 |
OrderBy(_ => Random.Shared.Next()) |
Shuffle() |
.NET 10 |
Range(0, 5).Select(i => i * 5) |
Sequence(0, 20, 5) |
.NET 10 |
The same releases also added new collection types, such as PriorityQueue, FrozenDictionary, OrderedDictionary and SearchValues, which often replace a LINQ pipeline that builds a lookup structure by hand.