Raju
Raju

Reputation: 207

to check whether the list of arrays has same value

I have a list of all integer array in which i want to check whether the list has same value i.e -1.

for ex.

int[] intk= {-1,-1,-1,-1,-1,-1};
int[] intl = { -1, -1, -1, -1, -1, -1 };
List<int[]> lst = new List<int[]>();
lst.Add(intk);
lst.Add(intl);

how to find lst has only -1 only.

Upvotes: 2

Views: 2784

Answers (3)

Denys Denysenko
Denys Denysenko

Reputation: 7894

This will work if you want to check to any same values not only -1.

var l = lst.SelectMany(_ => _);
bool areSame = l.All(_ => l.FirstOrDefault() == _);

Upvotes: 0

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

You can check that using the .All(...) extension method bundled with LINQ.

In order to create a list with both array items, you should use .AddRange(...) and the T parameter of List<T> should be int instead of int[]:

int[] intk= {-1,-1,-1,-1,-1,-1};
int[] intl = { -1, -1, -1, -1, -1, -1 };
List<int> lst = new List<int>();
lst.AddRange(intk);
lst.AddRange(intl);

And now you'll be able to use .All(...):

bool result = lst.All(item => item == 1);

...or:

bool result = lst.All(item => item == -1);

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Flatten your list with SelectMany and then check if all are same:

int value = -1;
bool allSame = lst.SelectMany(a => a).All(i => i == value);

Upvotes: 4

Related Questions