如何订购IEnumerable <t>的匿名类型?</t>

时间:2009-05-05 05:06:35

标签: c# .net-3.5 anonymous-types

请参阅下面的代码,我不知道为什么我的订单不起作用,有什么想法吗?

var orderSample = new { ProductName = "", Qty = 0, UserFullName = "" };
var ordersList = (new[] { orderSample }).ToList();

//loop thru another collection and fill ordersList by adding an order at a time
ordersList.Add(new { ProductName = "Product1", Qty = 5, UserFullName = "Mr. Smith" });

//sort the orders by name - DOESN'T WORK
ordersList.OrderBy(p => p.ProductName);

gvReport3.DataSource = ordersList;
gvReport3.DataBind();

1 个答案:

答案 0 :(得分:10)

var sortedList = ordersList.OrderBy(p => p.ProductName).ToList();

OrderBy()返回一个已排序的集合,它不会修改ordersList。

如果您需要修改ordersList,请改用Sort。