Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a list of string arrays. I make a new string array through an iteration and try to put it inside the list, but it doesn't check to see if it exists when i use the contain function, and instead inserts duplicates.

List<string[]> possibleColumnValues = new List<string[]>();

while(true){

  string[] rArr = new string[5];
  //some code to populate the string goes here

  if (!possibleColumnValues.Contains(rArr){
  {
      possibleColumnValues.Add(rArr);
  }
}
share|improve this question

4 Answers

up vote 1 down vote accepted

Still not very efficient but should do the trick:

if (!possibleColumnValues.Any(rArr.SequenceEqual))
{
    possibleColumnValues.Add(rArr);
}
share|improve this answer

The Contains method relies upon the Equals method of its elements to see if it contains a particular value. Arrays do not override the default implementation of Equals so Contains will only consider an array to be equal to one already within in the the list if it is a reference to the same object (the default behaviour of Equals).

To work around this you can use the Enumerable.Any() extension method along with the SequenceEqual extension method:

if (!possibleColumnValues.Any(item.SequenceEqual))
{
    possibleColumnValues.Add(rArr);
}
share|improve this answer

You can use Sequence equal method to compare two string arrays.

SequenceEqual extension from System.Linq in the C# language, you can test two collections for equality in one statement.

SequenceEqual

but its performance is much worse than alternative implementations.

or Implement your own Equals function

List.Contains Method

share|improve this answer
private static bool AllElementInList(List<string[]> list, string[] arr)
{
    return list.Select(ar2 => arr.All(ar2.Contains)).FirstOrDefault();
}

Use it as :

        List<string[]> list = new List<string[]>();
        string[] arr;

        bool flag = AllElementInList(list, arr);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.