Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a List<object> filled with anonymous types without LINQ

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?

like image 326
Ozzah Avatar asked Jan 17 '23 15:01

Ozzah


1 Answers

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) );
like image 100
Sergey Kalinichenko Avatar answered Jan 20 '23 16:01

Sergey Kalinichenko