Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .Where & .Select

Tags:

c#

I was looking into how to check character duplicates and I came across this method, it works, but I am trying to understand how it works. If anyone could explain this method so I can better understand what is occurring I would greatly appreciate it. Thank you.

static int duplicateAmount(string word)
{
    var duplicates = word.GroupBy(a => a)
        .Where(g => g.Count() > 1)
        .Select(i => new { Number = i.Key, Count = i.Count() });

    return duplicates.Count();
}
like image 716
Wiam Avatar asked Aug 16 '26 08:08

Wiam


2 Answers

The idea is to group the characters in the string and check if any group contains more than one elements, signifying duplicate occurrence of characters. For example, word.GroupBy would produce a grouping result as the following.

enter image description here

As you can observe, the characters t,i,and s has more than one occurrences. The Where condition filters the groups which has more than one element and the count method counts the numbers of filtered groups.

In your case, if you are interested only in counting the number of characters that are duplicate, you could refactor the method further as

static int duplicateAmount(string word)
{
    return word.GroupBy(a => a)
        .Count(g => g.Count() > 1);

}

This avoids creation of intermediate types, which is not quite required if you are interested only the count

like image 80
Anu Viswan Avatar answered Aug 17 '26 23:08

Anu Viswan


When you iterate a string, you do so by iterating all its characters.

Therefore:

static int duplicateAmount(string word)
{
    var duplicates = word.GroupBy(a => a) // Groups all the unique chars
        .Where(g => g.Count() > 1) // filters the groups with more than one entry
        // Maps the query result to an anonymous object containing the char 
        // and their amount of occurrences
        .Select(i => new { Number = i.Key, Count = i.Count() });
    // return the count of elements in the resulting collection
    return duplicates.Count();
}

Now that you have understood that, you can probably tell the last step (the mapping) is unnecessary since we're creating a structure we're not using at all: { Number, Count}.

The code can perfectly be

static int duplicateAmount(string word)
{
    return word.GroupBy(a => a) // Groups all the unique chars
            // Counts the amount of groups with more than one occurrence.
               .Count(g => g.Count() > 1); 
}

Edited: Removed the where clause as noted in the comments. Thanks @DrkDeveloper


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!