MikeS159
MikeS159

Reputation: 1964

C# - Search list of arrays for specific array

I am trying to find different combinations of values that will solve a solution. If the values (in a double array) pass a test I want to add them to a list, providing they are not already in the list.

If the list contains an array with values [1, 2, 3, 4, 5] and I check to see if the list contains array [5, 4, 3, 2, 1] List.Contains returns true. Is there anyway to search a list of arrays where order of the array matters?

I have tried List.Any(array.SequencyEqual) but that seems to have the same issue.

if(!myList.Any( a => a.SequenceEqual(myArray)))
{
    //some code to print array values 
    myList.Add(myArray);
}

This if statement executes true once, then never again.

Upvotes: 0

Views: 119

Answers (2)

Jodrell
Jodrell

Reputation: 35696

I fear you are mistaken, run this simple test program

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var list = new List<double[]>
            {
                new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }
            };
        Console.WriteLine(
            list.Any(a => a.SequenceEqual(new[] { 5.0, 4.0, 3.0, 2.0, 1.0 })));
        Console.WriteLine(
            list.Any(a => a.SequenceEqual(new[] { 1.0, 2.0, 3.0, 4.0, 5.0 })));
    }
}

this program outputs

False
True

as I would expect.

Upvotes: 4

adv12
adv12

Reputation: 8551

There's probably a fancy way to do this in LINQ, but here's the old fashioned way...

List<int[]> list = new List<int[]>();
int[] array1 = new int[]{ 1, 2, 3, 4, 5 };
int[] array2 = new int[]{ 5, 4, 3, 2, 1 };
list.Add(array1);
// add other arrays to list
bool found = false;
foreach (int[] other in list)
{
    bool isMatch = true;
    if (array2.Length == other.Length)
    {
        for (int i = 0; i < array2.Length; i++)
        {
            if (array2[i] != other[i])
            {
                isMatch = false;
                break;
            }
        }
    }
    else
    {
        isMatch = false;
    }

    if (isMatch)
    {
        found = true;
        break;
    }
}

Now, use found to decide what to do with your array.

Upvotes: 0

Related Questions