user13693463
user13693463

Reputation:

Implementation for a method that finds the first nonrepeatable character in a string using Linq, while crossing through the string only once

I have to implement a method that finds the first character from a string that does not repeat itself, while using Linq methods and not going through the string more than once. This is what i have so far, and, while it does use Linq methods, it crosses the string several times. Does anyone have any idea how to solve this?

public class StringUsingLinq
{
    string givenString;

    public char GiveTheFirstCharThatDoesntRepeat()
    {
        Func<char, bool> noRepeat= x => givenString.IndexOf(x) == givenString.LastIndexOf(x);
        return givenString.First(noRepeat);
    }
}

Upvotes: 0

Views: 60

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

public char? GiveTheFirstCharThatDoesntRepeat(string givenString)
{
    return givenString
        .GroupBy(c => c)
        .FirstOrDefault(grp => grp.Count() == 1)?
        .Key;
}

Note that char? should be used, because it is possible that the givenString may only have repeating characters.

Upvotes: 4

Related Questions