typestar

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

  1. DistinctBy(v => v.User) keeps the first visit per user.
  2. The elements survive intact — only the key drives the comparison.
  3. Counting by Page shows the same tool on a different key.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Slicing, step 6 of 17 in LINQ in depth.

← Previous Next →