1

I have a collection of an object called dictionaryWords.

For each word in this collection I need to check if it does not contain certain letters. If it does contain one or more of a certain letter it is removed from the collection.

Example:

Collection before removal: ['abc','dee',fff']
letters to check for: e,f
Collection after removal: ['abc']

Rather than specifying multiple letters is there a way to check against an array?

My code:

foreach(DictionaryWord word in dictionaryWords)
{
    if (!word.Contains("D") && !word.Contains("E") // optimize this line
    {
        // Word does not contain letters, word is good
    }
}

How can I replace the "optimize this line" to say "if word contains any letter from an array of values"

Thanks, Andrew

6 Answers 6

3

Try something like this:

// isolate the letters
string[] letters = new string[] { "D", "E", "F" }; // other strings or letters

// interate between your data
foreach(DictionaryWord word in dictionaryWords)
{
    // check if the work does not contain any letter
    if (!letters.Any(x => word.Contains(x))
    {
        // Word does not contain letters, word is good
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Why not abstract this out to a function?

void CheckForLetters(IEnumerable<DictionaryWord> source, IEnumerable<char> letters) {
  foreach (var word in source) { 
    if (letters.any(c => word.Contains(c)) { 
      // It has the letter
    }
  }
}

Comments

0

Create a method that accepts an array of characters to compare against.

The prototype would look like the following: bool isLetterInWord(DictionaryWord word, char[] letters);

Comments

0

Assuming that you can map your DictionaryWord class to a string, you can use a Linq query for this:

var words = new string[] { "abc", "def", "fe" };
var lettersToExclude = new char[] { 'e', 'f' };
var goodWords = from x in words where !lettersToExclude.Intersect(x).Any() select x;

Comments

0

Use HashSets and make use of IsSubsetOf method

http://msdn.microsoft.com/en-us/library/bb358446(v=vs.110).aspx

 string str = "teststing";

 var strset = new HashSet<char>(str.ToCharArray());
 var charstoCheck = new HashSet<char>(new Char[] {'z'});
 bool isstrcontainschars = charstoCheck.IsSubsetOf(strset);

Comments

0

You could use Regex for that.

string value = "abcdef";
var result = new Regex("[d-e-f]").Replace(value, string.Empty);

It checks if the string contains the letters at the Regex's constructor, and replace the letters for what you want. In my example, I replaced the letter to string.Empty.

In your case, you could do like this:

if (new Regex("[d-e-f]").IsMatch(word))
{
    //Do something.
}

Comments

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.