Steve Staple
Steve Staple

Reputation: 3279

string[].Contains does not find a match even if the text is in the array

I have put displays into my program, and can clearly see that the string being searched for is present.

Is it possible that there are 'invisible' characters preventing this from working?

    var items = new List<string>(currComponent.Split(new string[] 
    { "\r\n", "\n" }, StringSplitOptions.None));
    string feedback = string.Empty;
                foreach (string i in items)
                {
                    feedback += i + ". ";
                }
                ScriptingObject.WriteLogMessage
                 ("feedback:" + feedback + "<EOF>", true);
   if (items.Contains(attributeDescription))

The result of the display shows that the variable feedback contains the phrase 'Flue', but items.Contains("Flue") does not find it.

Message: Status message: 2015-01-09 10:36:18 | feedback:_ ,. Boiler Flue Type. 
Boiler make. Boiler Model. Gas Appliance Safety Protector. __.. . <EOF>

Next message: unable to process an Update Location record ...because of error:
item Flue not found .

Upvotes: 2

Views: 1986

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67080

Because string in items is not "Flue" but "Boiler Flue Type" and List.Contains() searches for an exact match, remember you're calling List.Contains() not String.Contains().

Note that there is a simpler way to join your strings:

string feedback = String.Join(". ", items);

With LINQ you may use this:

if (items.Any(x => x.Contains(attributeDescription))) { }

If you do not explicitly need a List<string> you may also keep String.Split() return type (string[]), to put all together:

var items = currComponent.Split(new string[] { "\r\n", "\n" },
    StringSplitOptions.None);

ScriptingObject.WriteLogMessage("feedback: " 
    + String.Join(". ", items)
    + "<EOF>", true);

if (items.Any(x => x.Contains(attributeDescription))) {
}

Upvotes: 6

Related Questions