Random r = new Random();
List<object> myList = new List<object>();
for (int i = 0; i < 100; i++)
myList.Add(new { A = r.Next(), B = r.Next() });
myList.Sort( (obj1, obj2) => obj1.A.CompareTo(obj2.A) );
The above code defines a generic List
an populates it with 100 anonymous variables with two members, A and B.
Let's say I want to sort myList on A. The final line attempts to sort the list, however this code clearly doesn't compile because the compiler doesn't know what the list of objects contains.
Without using LINQ, is it possible to somehow sort this list using a lambda or similar?
It is possible to sort it without LINQ, as long as you manage to declare your list as that of a List of objects of anonymous type using the var
syntax, or are willing to use dynamic
:
Random r = new Random();
List<dynamic> myList = new List<object>();
for (int i = 0; i < 100; i++)
myList.Add(new { A = r.Next(), B = r.Next() });
myList.Sort( (obj1, obj2) => obj1.A.CompareTo(obj2.A) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With