Sort list <object> populated 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 code above defines a generic code Listthat fills it with 100 anonymous variables with two members, A and B.

Let's say I want to sort myList by A. The last line tries to sort the list, however this code does not explicitly compile because the compiler does not know what the list of objects contains.

Without using LINQ, is there any way to sort this list using lambdas or the like?

+3
source share
3 answers

LINQ, var 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) );
+6

-, LINQ, :

var myList = Enumerable.Range(0, 100)
                       .Select(index => new { A = r.Next(), B = r.Next() })
                       .ToList();
myList.Sort( (obj1, obj2) => obj1.A.CompareTo(obj2.A) );

-, dynamic, List<dynamic>, LINQ.

, . , , LINQ!

+2

LINQ - , .

You want something like this to create a list of your type (similar to the extension ToList()):

List<T> NewList<T>(T ignored)
{
    return new List<T>();
}

and use it as

Random r = new Random();
var myList = NewList(new { A = r.Next(), B = r.Next() });

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) );
+1
source

All Articles