Removing strings with duplicate letters from string array

Viewed 51

I have array of strings like

string[] A = { "abc", "cccc", "fgaeg", "def" };

I would like to obtain a list or array of strings where any letter appears only one time. I means that "cccc", "fgaeg" will be removed from input array. I managed to do this but I feel that my way is very messy, unnecessarily complicated and not efficient.

Do you have any ideas to improve this algorythm (possibliy replacing with only one Linq query)?

My code:

        var goodStrings = new List<string>();
        int i = 0;
        foreach (var str in A)
        {
            var tempArr = str.GroupBy(x => x)
                .Select(x => new
                {
                    Cnt = x.Count(),
                    Str = x.Key
                }).ToArray();

            var resultArr = tempArr.Where(g => g.Cnt > 1).Select(f => f.Str).ToArray();
            if(resultArr.Length==0) goodStrings.Add(A[i]);
            
            i++;
        }
1 Answers

You can use Distinct method for every array item and get items with count of distinct items equals to original string length

string[] A = { "abc", "cccc", "fgaeg", "def" };
var result = A.Where(a => a.Distinct().Count() == a.Length).ToList();

You'll get list with abc and def values, as expected

Related