1

if we have a 1D array, we could use the following to see if all elements are equal to 3:

int[] t = Enumerable.Repeat(3, 10).ToArray();

if (t.All(item => item.Equals(3))) MessageBox.Show("all elements equals to 3");

but if I have a 2D-array, how could I check if all elements are equal to 3 ( without any for-Loops ):

    int[,] t2D= new int[,] { { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 } };

    if( CHECK IF ALL ELEMENTS IN **t2D** are equal to 3) 

               {
                MessageBox.Show("all elements equals to 3");
               }

What should I put in If-statement?

2
  • 3
    Without any for loops? ok... Considered that All() is using for loops? No need to be ashamed of for() or foreach() Commented Nov 15, 2012 at 1:09
  • @lboshuizen: If you define a 2D array: int[,] tt = new int[3, 4]; .All() is not part of the methods that you could use. Try tt.All => no method has been defined for 2D array case Commented Nov 15, 2012 at 3:08

1 Answer 1

3

2D-array is an enumerable type (but it implements non-generic IEnumerable). And it's enumerator enumerates over all items in 2D-array. So, only thing you need to do - cast its items to int (thus retrieving IEnumerable<int>) and apply All

t2D.Cast<int>().All(x => x == 3)
Sign up to request clarification or add additional context in comments.

2 Comments

@ lazyberezovsky: aw,thanks. just for the purpose of learning, how could I differentiate between non-generic Inumerable and generic Inumerables? or lets rephrase it: why generic types support .All() method or non-generic not?
@farzinparsa All() is an extension method on type IEnumerable<T> (defined in Enumerable class)or IQueryable<T>. Thats why only generic sequences support Linq methods.

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.