3

If I have the following string:

string s = "abcdefghab";

Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab".

Although not necessary, I was trying to do this in a single line of LINQ and had so far come up with:

s.ToCharArray().OrderBy(a => a)...

3 Answers 3

7
String text = "dssdfsfadafdsaf";
var repeatedChars = text.ToCharArray().GroupBy(x => x).Where(y => y.Count() > 1).Select(z=>z.Key);
Sign up to request clarification or add additional context in comments.

Comments

7
string theString = "abcdefghab";

//C# query syntax
var qry = (from c in theString.ToCharArray()
           group c by c into g
           where g.Count() > 1
           select g.Key);

//C# pure methods syntax
var qry2 = theString.ToCharArray()
            .GroupBy(c => c)
            .Where(g => g.Count() > 1)
            .Select(g => g.Key);

Comments

7

Also, a string is an IEnumerable already, so you don't really need to call ToCharArray();

var qry = (from c in theString
           group c by c into g           
           where g.Count() > 1           
           select g.Key);

That leave qry as an IEnumerable, but if you really need a char[], that as easy as qrt.ToArray().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.