IntermediateLesson 9 of 16
LINQ: Querying Data – C#
Filter, transform, sort and group with one consistent syntax.
LINQ (Language Integrated Query) provides extension methods for everything that is an IEnumerable<T>: lists, arrays, dictionaries, database queries (Entity Framework) and more. The most important ones: Where (filter), Select (transform), OrderBy (sort).
var zahlen = new[] { 5, 3, 8, 1, 9, 2 };
Console.WriteLine(string.Join(",", zahlen.Where(z => z % 2 == 0))); // 8,2
Console.WriteLine(string.Join(",", zahlen.Select(z => z * z))); // 25,9,64,1,81,4
Console.WriteLine(string.Join(",", zahlen.OrderBy(z => z))); // 1,2,3,5,8,9
Console.WriteLine(zahlen.Sum()); // 28
Console.WriteLine(zahlen.Max()); // 9
Console.WriteLine(zahlen.Count(z => z > 3)); // 3With objects you get readable queries. GroupBy groups, First/FirstOrDefault return the first element, Any/All test conditions.
var personen = new List<Person>
{
new("Ada", 36, "London"),
new("Bob", 25, "Berlin"),
new("Cem", 41, "Berlin")
};
var berliner = personen.Where(p => p.Stadt == "Berlin")
.OrderBy(p => p.Alter)
.Select(p => p.Name);
Console.WriteLine(string.Join(", ", berliner)); // Bob, Cem
foreach (var g in personen.GroupBy(p => p.Stadt))
Console.WriteLine($"{g.Key}: {g.Count()}"); // London: 1 / Berlin: 2
Console.WriteLine(personen.Any(p => p.Alter > 40)); // True
record Person(string Name, int Alter, string Stadt);Deferred execution is important: a LINQ query only runs when you iterate over it or evaluate it with ToList(), ToArray(), Count() and so on.
var liste = new List<int> { 1, 2, 3 };
var abfrage = liste.Where(x => x > 1); // nothing executed yet
liste.Add(10);
Console.WriteLine(abfrage.Count()); // 3 (2, 3 and 10)
var fest = liste.Where(x => x > 1).ToList(); // snapshot
liste.Add(20);
Console.WriteLine(fest.Count); // 3WarningIf you evaluate the same query several times, it runs several times (and, for example, reads from the database several times). Materialize the result with
ToList() if you want to reuse it.TipBesides method syntax there is the SQL-like query syntax:
from p in personen where p.Alter > 30 select p.Name. Both produce the same code.