DistinctBy in C#
Deduplicate by a key while keeping whole elements.
var visits = new[]
{
(User: "ada", Page: "/home"), (User: "alan", Page: "/docs"),
(User: "ada", Page: "/docs"), (User: "kurt", Page: "/home"),
};
// DistinctBy keeps the first element seen for each key
var firstPerUser = visits.DistinctBy(v => v.User);
foreach (var (user, page) in firstPerUser)
{
Console.WriteLine($"{user} landed on {page}");
}
Console.WriteLine(visits.DistinctBy(v => v.Page).Count());
How it works
DistinctBy(v => v.User)keeps the first visit per user.- The elements survive intact — only the key drives the comparison.
- Counting by
Pageshows the same tool on a different key.
Keywords and builtins used here
foreachinnewvar
The run, in numbers
- Lines
- 13
- Characters to type
- 406
- Tokens
- 104
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 73 seconds.
Step 3 of 3 in Slicing, step 6 of 17 in LINQ in depth.