LINQ
This one’s kind of interesting. It’s called Language Integrated Query, and it lets you write sql-like queries in C#. Anything enumerable can use it.
/// Without LINQ
var result = new List<string>();
foreach (var f in files)
{
if (f.Contains(keyword))
result.Add(f);
}
/// With LINQ
var result = files.Where(f => f.Contains(keyword)).ToList();
Common methods:
| Method | What it does |
|---|---|
.Where() | Filter (a filter condition) |
.Select() | Transform (this is map, runs your own function on each element) |
.FirstOrDefault() | Take the first one, null if there isn’t one |
.Any() | Whether any element matches |
.Count() | Count |
.OrderBy() | Sort |
.ToList() / .ToArray() | Materialize the result |
And the key here is that the query description and the actual execution are separate, so you have to use ToList() or ToArray() to run it right away, or call that later when you need it.
List and Array are about the same most of the time, but the biggest difference is that the first can grow and shrink whenever, and the second is fixed. For cases that won’t change, the second fits better, since performance is higher. If you need to add and remove at will, you have to use the first.
Translation note. I wrote this in Chinese. This English version is an LLM translation, so the wording is not mine even though the thinking is. Original: LINQ.