1

I am comparing strings with .Contains() but I found a problem:

foreach (var pair in cluster)
{
    if (pair.Key.Contains("a" + i.ToString()))
    {
         vlr = pair.Value;
    }
}

"a10", "a11", "a1.." are retrieving when I search "a1". There is another way to compare diferente of ==

2
  • I forgot! using contais: pair.key is ("a5-a6", "a1-a8", "a10-a7") and the error occours when I need to find "a1".... The code must retrieve only "a1-a8" and not "a1-a8" and "a10-a7". I guess I have to splitted .Split('-') and compare both results separated... Commented May 23, 2013 at 2:41
  • It would be more helpful if you edited your question with that detail rather than burying it in a comment. Commented May 23, 2013 at 2:50

3 Answers 3

1

Based on your comment I think the query you're looking for is:

var query = cluster.Where(kvp => kvp.Key
                                    .Split('-')
                                    .Contains("a" + i.ToString())  // Array.Contains, not String.Contains
                         )
                   .Select(kvp => kvp.Value);
Sign up to request clarification or add additional context in comments.

Comments

1

If you would like to make sure that your search string is an isolated substring, not a prefix or a suffix of a larger substring, you can use regular expressions. For example, to see if a string contains a5 but not a52 or xa5, you can do this:

if (Regex.Matches(input, "\\ba5\\b").Count > 0) ...

Here is an example:

Console.WriteLine(Regex.Matches("hello a5 world", "\\ba5\\b").Count > 0);  // True
Console.WriteLine(Regex.Matches("hello a55 world", "\\ba5\\b").Count > 0); // False
Console.WriteLine(Regex.Matches("hello xa5 world", "\\ba5\\b").Count > 0); // False

Here is a demo on ideone.

Regex is versatile enough to let you adjust the expression to your needs: you can use positive and negative lookahead/lookbehind. For example, if you need to make sure that 5 is not followed by another digit, you can write "a5(?!\\d)".

Comments

0

.Contains() checks if the string contains a sub string in it or string

if you trying to see if they are equal or not you should use somethink like

if (pair.Key.Equals(i.ToString()))

or

string.Compare(pair.Key, i.ToString()) == 0

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.