Ramie
Ramie

Reputation: 1201

Check if string array exists in list of string

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);
  }
}

Upvotes: 1

Views: 11950

Answers (4)

Parimal Raj
Parimal Raj

Reputation: 20575

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);

Upvotes: 4

DotNetUser
DotNetUser

Reputation: 6612

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

Upvotes: 1

Paul Ruane
Paul Ruane

Reputation: 38580

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);
}

Upvotes: 1

empi
empi

Reputation: 15881

Still not very efficient but should do the trick:

if (!possibleColumnValues.Any(rArr.SequenceEqual))
{
    possibleColumnValues.Add(rArr);
}

Upvotes: 1

Related Questions