sequential autogenerated Id with help of linq

Miral picture Miral · Aug 4, 2009 · Viewed 8.6k times · Source

I have a class Booking

public class Booking
    {
        public int Id { get; set; }

        public string From { get; set; }

        public string To { get; set; }
    }

I create a List bookings with the help of linq and I want some mechanism with which I want to autogenerate the 'Id' property to increment by 1.

I.e. if the List bookings contains 10 Booking object then the first object's Id = 1, second Id = 2 and so one...

any suggestion

Answer

Scott Ivey picture Scott Ivey · Aug 4, 2009

The following will give you a list of NEW bookings with the index projected into your ID property. You could probably do something similar to this to update the existing list with the index...

var myBookings = myExistingListOfTen.Select((b, index) => new Booking
                 {
                     Id = index + 1, 
                     From=b.From, 
                     To=b.To
                 });