Adam Weitzman Adam Weitzman - 1 month ago 7
C# Question

Save Duplicate Values From String

I have:

string turtle = "turtle"
var charArray = turtle.ToCharArray()


When I do:

var distinct = charArray.Distinct().ToArray()
// distinct = ["t","u","r","l","e"]


My question is:

How do I save the characters that got deleted from
charArray
when I called Distinct on it? How do I get the variable distinct to equal
"t"
(the character that was removed)

Thanks!

Answer

Use GroupBy to return only the letters having count > 1:

string turtle = "turtle";
var dups = (from l in turtle
            group 1 by l into g
            where g.Count() > 1
            select g.Key).ToList();
Comments