对List< object>进行排序.没有LINQ的匿名类型填充 [英] Sorting a List<object> filled with anonymous types without LINQ

查看:78
本文介绍了对List< object>进行排序.没有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) );

上面的代码定义了一个通用的List,并在其中填充了100个具有两个成员A和B的匿名变量.

The above code defines a generic List an populates it with 100 anonymous variables with two members, A and B.

假设我要对A上的myList进行排序.最后一行尝试对列表进行排序,但是由于编译器不知道对象列表包含的内容,因此该代码显然无法编译.

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.

在不使用LINQ的情况下,是否可以使用lambda或类似名称对列表进行排序?

Without using LINQ, is it possible to somehow sort this list using a lambda or similar?

推荐答案

只要使用var声明为匿名类型的对象列表,就可以在不使用LINQ的情况下对其进行排序.语法,还是愿意使用dynamic:

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

这篇关于对List&lt; object&gt;进行排序.没有LINQ的匿名类型填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆