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
varsyntax, or are willing to usedynamic: