Anonymous type, Enumerator and Lambda expression

Via:

var Foo = new[]{ new {Something = 321}}; 

Why can I do (compile):

  Console.WriteLine( Foo[0].Something ); 

but not:

  Foo.ForEach(x => Console.WriteLine(x.Something)); 
+6
source share
2 answers

Because Array only has a static ForEach method:

 var Foo = new[] { new { Something = 321 } }; Array.ForEach(Foo, x => Console.WriteLine(x.Something)); 

compiles and works.

+7
source

to try

  Foo.ToList().ForEach(x => Console.WriteLine(x.Something)); 

since the ForEach extension is only available for lists

EDIT : tested and working.

EDIT2 : Some Workarounds for Creating an Anonymous List

This is SO post
This blog post
Another blog post

+4
source

Source: https://habr.com/ru/post/910894/


All Articles