How to get an array of duplicate characters from a string using LINQ?

If I have the following line:

string s = "abcdefghab";

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

Although not required, I tried to do this on a single LINQ line and still came up with:

s.ToCharArray().OrderBy(a => a)...
+3
source share
3 answers
String text = "dssdfsfadafdsaf";
var repeatedChars = text.ToCharArray().GroupBy(x => x).Where(y => y.Count() > 1).Select(z=>z.Key);
+7
source
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);
+7
source

, IEnumerable, ToCharArray();

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

This leaves qry as IEnumerable, but if you really need char [], it's as simple as qrt.ToArray().

+7
source

Source: https://habr.com/ru/post/1698837/


All Articles