2

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.

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Tigran thanks! Your answer is correct for single array, but there is list of arrays in question
0

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

Comments

0

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() == _);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.