Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
static List<int[,]> list = new List<int[,]>();
int[,] array={{1,1},{2,2}};
list.Add(array);

foreach(var element in list)
if(element==array)//return -1!!!!!! why?????
{
//
}
Posted
Comments
CHill60 13-Jan-15 11:04am    
Insufficient information - please update your question with an actual question
Sergey Alexandrovich Kryukov 13-Jan-15 11:10am    
List of arrays and array are very different types, so, what is the comparison criteria?
(When you formulate them, you will already be close to the answer.)
—SA

You could use SequenceEqual. This works for any IEnumerable<t>, not just arrays
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 13-Jan-15 11:36am    
Good idea, but only if the inquirer wants that; I would prefer to ask him first. List of arrays is two-level hierarchy, so maybe hierarchy should be flatten in certain way, or maybe he does not understand what he wants (also pretty likely), and so on.
Also, you should better provide a link.
—SA
BillWoodruff 13-Jan-15 20:18pm    
There's a problem with SequenceEquals here because the OP is using two-dimensional Arrays; SequenceEquals will not work on multi-dimensional Arrays; there are ways to work around that, but they are kind of ugly. Example:

private string[] a1 = new[] {"1", "2", "3"};

private string[] a2 = new[] { "3", "4", "5" };

private string[] a3 = new[] { "1", "2", "3" };

private string[] a4 = new[] { "3", "4", "5" };

private List<string[]> a5;

private List<string[]> a6;

private void Test()
{
a5 = new List<string[]>{a1,a2};

a6 = new List<string[]>{a3,a4};

bool result1 = a5[0].SequenceEqual(a6[0]); // true

bool result2 = a5[1].SequenceEqual(a6[1]); // true

bool result3 = a5.SequenceEqual(a6); // false
}
Your code will work as it is.

Do keep in mind that the reason it works is because you are comparing Value Types ... Ints ... not Reference Types !

here I am using the same comparison that you use, I've just packaged into a function:
C#
static List<int[,]> list = new List<int[,]>();
int[,] array={{1,1},{2,2}};

public bool isInArray(List<int[,]> list1, int[,] array)
{
    foreach (var subArray in list1)
    {
        if (subArray == array)
        {
            return true;
        }
    }

    return false;
}

// test in some method or EventHandler:

list.Add(array);

bool test = isInArray(list, array);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900