Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 291
Miral Avatar asked Dec 01 '22 11:12

Miral


1 Answers

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
                 });
like image 159
Scott Ivey Avatar answered Dec 09 '22 13:12

Scott Ivey