Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoincrement Id in list

Im looking for a way to give my list-objects an Id that autoincrements from 1 to (however many).

This is the class I use

public class Movie
{

    public int Id { get; set; }
    public string Title { get; set; }
    public string Director { get; set; }
}

I will use this as a list like so:

 public List<Movie> Movies { get; set; }

Now lets say that the list contains 10 movies and I delete movie with id 5. I would like the id´s on all movies to change so that the movie that used to have id 6 now has id 5. Can someone point me in the right direction?

like image 405
user2915962 Avatar asked Mar 16 '26 16:03

user2915962


2 Answers

How about creating a wrapper for your movies list and letting that class handle the Ids?

public class MoviesList
{
    public List<Movie> Movies;

    public MoviesList()
    {
        Movies=new List<Movie>();
    }

    public void Add(Movie movie)
    {
        var highestId = Movies.Any() ? Movies.Max(x => x.Id) : 1;
        movie.Id = highestId + 1;
        Movies.Add(movie);
    }
}
like image 147
Mohammad Sepahvand Avatar answered Mar 18 '26 06:03

Mohammad Sepahvand


This may be simplistic, but why not use the index of the List itself as the id? It would work nicely for the scenario you describe. Then you don't need an Id property inside the Movie class.

If you have a more complex case which you haven't described, you may need to implement something like a reference counter to keep track of all the Movie life-cycles.

like image 36
metacubed Avatar answered Mar 18 '26 05:03

metacubed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!