Check if string array exists in string list

I have a list of string arrays. I create a new array of strings through iteration and try to put it in a list, but it does not check if it exists when I use the contains function and inserts duplicates instead.

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); } } 
+1
source share
4 answers
 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); 
+3
source

Still not very effective, but should do the trick:

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

The Contains method relies on the Equals method of its elements to see if it contains a specific value. Arrays do not override the default implementation of Equals , so Contains will only consider an array that will be equal to the unit already included in the list if it is a reference to the same object (the default behavior is Equals ).

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

 if (!possibleColumnValues.Any(item.SequenceEqual)) { possibleColumnValues.Add(rArr); } 
+1
source

You can use the Sequence sequence method to compare two string arrays.

Extending the SequenceEqual from System.Linq in C #, you can check two collections for equality in one statement.

Sequencequal

but its performance is much worse than alternative implementations.

or execute your own Equals function

List.Contains Method

+1
source

All Articles