Is there a neater way to get the last 12 records in a loop .net 2.0

I am used to linq now and going back to .net 2.0 is a pain.

I need to get the last 12 records by date.I build a noddy sample to explain the problem.I am not happy with the way I coded it. I used reverse on a list to do the job.

Is there a neater way?

here is my code:

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

any suggestions on how to improve the above code to get the last 12 records?

Thanks

Jon Skeet
people
quotationmark

You've got a List<Order> - that means you know the count, and the GetRange method.

var allOrders = BuildOrders();
// Take at most 12, but don't try to take more orders than actually exist!
int rangeCount = Math.Min(12, allOrders.Count);
var lastOrders = allOrders.GetRange(allOrders.Count - rangeCount, rangeCount);

You should also consider using LINQBridge - a LINQ to Objects implementation for .NET 2.0.

people

See more on this question at Stackoverflow