0

Supposing I have a List<int> its easy to search for an integer, lets say 6

List<int> list = new List<int>(){1, 2, 3, 4, 5};
if(list.Contains(6))
   Console.Write("6 exists");

but how would I search for a int[] in a List<int[]>

List<int[]> example = new List<int[]>();
example.Add(new int[4]{0,1,2,3});
example.Add(new int[4]{10,11,12,13});
example.Add(new int[4]{20,21,22,23});

How to search for {0,1,2,3} and also delete that index on list?

int[] toFind = new int[4]{0,1,2,3};
foreach (int[] item in list)
{
   if(item.Length == toFind.Length)
   {
       bool found = false;
       for(int i=0; i < item.Length;i++)
       {
          if(item[i] == toFind[i])   
          {
              found = true;
          }
           else
          {
              found = false;
           }
       }
   }
}

I was trying to first compare wanted item length with each item length, the compare each item on array. There must be a better way to do this...

Edgar
  • 489
  • 2
  • 14

2 Answers2

6

You can use FindIndex() and the Linq extension SequenceEquals:

int index = list.FindIndex(arr =>  arr.Length == toFind.Length && arr.SequenceEqual(toFind));
if (index >= 0) list.RemoveAt(index);

Note that SequenceEqual returns true only if the elements in the sequence are in the same order. So {1,2,3,4} is not the same as {2,1,4,3}.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • Note this will be relatively slow for searching large data sources. [Using the Boyer-Moore algorithm](http://stackoverflow.com/questions/16252518/boyer-moore-horspool-algorithm-for-all-matches-find-byte-array-inside-byte-arra) can give you significant performance gains. – Scott Chamberlain Feb 07 '17 at 18:25
  • 1
    @ScottChamberlain I agree, this is not the fastest way. Maybe OP specifies in the question what "better way" means: faster, more readable or something else. – René Vogt Feb 07 '17 at 18:26
  • 1
    @Edgar I added a length check to make it faster. now I actually can't think of an algorithm to make it even faster. Unless you want to use this many times for different arrays checking against the _same list of arrays_. In this case, some way of hashing/indexing the arrays in the list could help. But if the overhead will pay off really depends on how often you really search in the same list. For a small number of searches I think my code does not leave much room for optimization. – René Vogt Feb 07 '17 at 21:08
1

You aren't allowed to change a List object in a foreach loop, but you can use a for loop instead.

private void removeFromList(List<int[]> list, int[] compare) {
   for (int i = 0; i < list.Count; i++) {
      if (list[i] == compare) {
         list.RemoveAt(i);
       }
     }
}
bwoogie
  • 4,339
  • 12
  • 39
  • 72