5

Instead of looping over my string I'd like to use LINQ. How to do the following?

//  explode our word
List<char> rackBag = new List<char>();
rackBag.AddRange("MYWORD??".ToCharArray());

// How many wildcards?
int wildCardCount = rackBag.Count(x => x.Equals("?"));

wildCardCount should equal 2.

2
  • 3
    Err... your are using linq already, aren't you?
    – AHM
    Oct 5, 2010 at 19:27
  • I am, but it wasn't working because of the double quotes. And I was hinting towards don't give me a for() solution
    – ryan
    Oct 6, 2010 at 11:17

4 Answers 4

25

Lots of unneeded steps there. Try this:

int wildCardCount = "MYWORD??".Count(x => x == '?');
6
rackBag.Count(x => x == '?'); 
1
  • 1
    Since x is a char, it isn't equal to the string value "?"
    – bdukes
    Oct 5, 2010 at 19:32
1

int wildCardCount = rackBag.Count(x => x=='?');

1

Regex is a possible way to count up the number of wildcards, as an alternative to the suggestions using Linq. Since the ? letter means something in Regexes, we have to escape it in the example (and use verbatim string @):

int howManyWildcards = Regex.Matches("MYWORD??", @"\?").Count;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.