Search code examples
c#linqsequenceauto-generate

sequential autogenerated Id with help of linq


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


Solution

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