4
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?


First, you can use LINQ if you use implicit typing very carefully:

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) );

Second, if you're willing to use dynamic, type the list as a List<dynamic> and then you can use LINQ directly.

However, I really don't see why you insist on being glued to anonymous types. Just make a nominal type and bask in the glory that is strong-typing, compile-time safety, and LINQ!

4

3 に答える 3

6

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) );
于 2012-05-22T01:28:03.257 に答える
2

まず、暗黙の型付けを非常に慎重に使用すれば、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 の栄光に浸ることができます。

于 2012-05-22T01:26:48.700 に答える
1

LINQには魔法はありません。すべてのメソッドシグネチャを調べて、型がどのように計算されるかを確認できます。

あなたはこのようなものがあなたのタイプのリストを作成することを望みます(ToList()拡張子に似ています):

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

として使用します

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) );
于 2012-05-22T01:33:45.733 に答える