locked
incrementing an ID column RRS feed

  • Question

  • User1094877758 posted

    Whenever I'm adding a new object from the front end, the id = 0.  In the WebApi layer, I'm trying to find the max ID that exists in the list of events and then assign the next ID to the new objects.  The code below doesn't increment the ID correctly

    List<Event> events = eventVal.Where(e => e != null).ToList();
    int eventMaxID = events.Max(e => e.id);
    
    events.Select(e => e.id == 0)
          .Select((e, ixc) => new { id = eventMaxID + 1, Iter = eventMaxID + 1 })
          .ToList();

    I'm not sure how to use the second parameter for the Select method.

    Any help would be appreciated! Thanks.

    Tuesday, July 11, 2017 3:56 PM

All replies

  • User1930269528 posted

    I believe you need to put Where in the first line and then Project those using Select which would be:

    events.Where(e => e.id == 0)
          .Select((e => new { id = eventMaxID + 1, Iter = eventMaxID + 1 })
          .ToList();

    Hope it helps!

    Tuesday, July 11, 2017 4:54 PM
  • User-707554951 posted

    Hi rds80,

    For you have get the max ID, why you don’t  new a Event object using the max ID,

      protected void Page_Load(object sender, EventArgs e)
            {
                List<Event> events = new List<Event>();
                events.Add(new Event() { id = 0, Iter = 2 });
                events.Add(new Event() { id = 3, Iter = 2 });
                events.Add(new Event() { id = 4, Iter = 2 });
                int eventMaxID = events.Max(s => s.id);
    //new a Event object using the max ID,
                Event eventnew=new Event() { id = eventMaxID+1, Iter = eventMaxID + 1 };
                events.Add(eventnew); // int eventMaxID = events.AsEnumerable().OrderByDescending(o => o.id).FirstOrDefault().id; // var eventnew= events.Where(w => w.id == 0).Select(s => new { id = eventMaxID + 1, Iter = eventMaxID + 1 }).ToList();
    //events.Add(eventnew);
    } public class Event{ public int id { get; set; } public int Iter{ get; set; } }

    Best regards

    Cathy

    Wednesday, July 12, 2017 8:07 AM