2

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
  • 2
    I think, the check could be done with Regex, something like ".*(\w).*\1.*" Commented Jun 25, 2020 at 13:04

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Very nice approach. It didn't cross my mind. Simple and clean.
Also if strings can be long enough it might be worth it to get rid of all string with more than 26 character right of the bat.
@Franck Thank you, that's the good point. However, OP didn't mentioned such requirements, like string length or used alphabet

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.