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?
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With