2

I've got this code:

for (int i = listboxWork.Items.Count-1; i > -1; i--) 
{
    if (listboxWork.Items[i].Contains(tblSent))
    {
        listboxWork.Items.RemoveAt(i);
    }
}

...which I derived from here, but my creaky old version of .NET (or maybe it's my puny version of .NET (Compact Framework) that's the problem) doesn't contain "Contains".

I reckon I could replace that line with:

if (listboxWork.Items[i].ToString().IndexOf(tblSent) > -1)

...but am not overly confident that's the best way to do it. Is there a more acceptable way?

Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    array might not have a contains operator, but are you sure that a list object doesnt? You could reverse the list and do a foreach. – crthompson Oct 07 '14 at 18:15

1 Answers1

2

Items is a collection of objects, so you need to convert the element you are working with to a string before you can use Contains:

if (listboxWork.Items[i].ToString().Contains(tblSent))

Edit: since this is CompactFramework (which I failed to recognize in the post originally, the proper solution is to use String.IndexOf, which was already identified.

This is a perfectly acceptable mechanism, but if the CF supports it, I would strongly suggest using a case-insensitive comparison, especially if there is any user input involved in the evaluation:

if (x.Items[0].ToString().ToLower().IndexOf(tblSent.ToLower()) != -1)
competent_tech
  • 44,465
  • 11
  • 90
  • 113