我现在习惯了 linq,回到 .net 2.0 很痛苦。
我需要按日期获取最后 12 条记录。我构建了一个 noddy 示例来解释问题。我对我的编码方式不满意。我在列表中使用反向来完成这项工作。
有没有更简洁的方法?
这是我的代码:
class Program
{
private static void Main(string[] args)
{
var allOrders = BuildOrders();
//Reverse so that we can get the orders in date desc and easier to get last 12
allOrders.Reverse();
int count = 0;
List<Order>onlyLast12Orders=new List<Order>();
foreach (Order order in allOrders)
{
count++;
if(count>12)break;
onlyLast12Orders.Add(order);
}
//Reverse again so that it can be displayed in date order
onlyLast12Orders.Reverse();
foreach (Order ord in onlyLast12Orders)
{
Console.WriteLine("Order Name :{0} Date: {1}", ord.Name, ord.Date);
}
Console.Read();
}
private static List<Order> BuildOrders()
{
List<Order> allOrders = new List<Order>();
for (int i = 0; i < 30; i++)
{
Order order = new Order("Order" + i, new DateTime(2013, 1, 1).AddDays(i));
allOrders.Add(order);
}
return allOrders;
}
}
public class Order
{
public Order(string name ,DateTime date)
{
this.name = name;
this.date = date;
}
private string name;
private DateTime date;
public string Name
{
get { return name; }
set { name = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
关于如何改进上述代码以获取最后 12 条记录的任何建议?
谢谢