tags:

views:

566

answers:

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)...
+5  A: 
String text = "dssdfsfadafdsaf";
var repeatedChars = text.ToCharArray().GroupBy(x => x).Where(y => y.Count() > 1).Select(z=>z.Key);
Andrew Theken
+6  A: 
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);
TheSoftwareJedi
+6  A: 

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().

James Curran