Junior — Middle
Can you list and explain the main methods of working with LINQ in C#?
sobes.tech AI
Answer from AI
The main LINQ methods in C# can be divided into several categories:
-
Filtering:
Where— selects elements that satisfy a condition.
-
Projection:
Select— transforms each element in the sequence.SelectMany— projects each element into a collection and flattens the result.
-
Sorting:
OrderBy,OrderByDescending— sort by a key.ThenBy,ThenByDescending— perform additional sorting.
-
Aggregation:
Count,Sum,Average,Min,Max— compute aggregate values.
-
Joining:
Join— joins two sequences based on a key.GroupJoin— groups elements from the second sequence.Concat— concatenates two sequences.Distinct— removes duplicates.
-
Grouping:
GroupBy— groups elements by a key.
-
Elements:
First,FirstOrDefault,Single,SingleOrDefault,Last,LastOrDefault— return elements based on a condition.
-
Condition checks:
Any— checks if any elements satisfy a condition.All— checks if all elements satisfy a condition.
Example of usage:
var numbers = new List<int> {1, 2, 3, 4, 5};
var evenSquares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n);
foreach(var num in evenSquares)
{
Console.WriteLine(num); // Outputs 4 and 16
}
LINQ allows writing expressive and concise code for working with collections and data.