C# If Item is not in array


What I want to be able to do, in C#, is not do something if the item is in an array.

I have a for loop going through a list of items, and it is modifying them. There are some of them that I don't want modified, and I have stored the text of them in a pre-defined array. What I want, is the for loop to go through the array of elements that I want modified, but if the text matches any of the items in another array that I have defined, to not do anything.

Is there any easy way to do this?

Who is Participating?
shman911Connect With a Mentor Commented:
iosgood's solution works if you're using a List.  But if you must keep those strings in an array, then you can use the System.Array.Sort() and then System.Array.BinarySearch().  See the example below.  BinarySearch will return an int equal to or greater than zero if the string is found in the array, and will return a negative number if not found.

The only downside is that Sort() will change the ordering of the strings in the array.  If the ordering is important, then you can't sort, and therefore you can't use BinarySearch.

string [] strArr = new string[] {"peter", "fred", "bob"};
System.Array.BinarySearch(strArr, "bob"); //returns int >= 0
System.Array.BinarySearch(strArr, "eric"); //returns int < 0

Open in new window

If you make a generic List of don't modify strings as in
   List<string> dontModify= new List<string>();

and then add each text string that shouldn't be modified to the List

then you can
   struct Item {
      public string someText;
   Item myItem = new Item(); // you'll have to initialize it correctly, of course
   if (dontModify.Contains(myItem.someText)) Console.WriteLine("Don't change");

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.