Autoincrement Id in list
Solution 1
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);
}
}
Solution 2
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.
Solution 3
You can create something like your custom collection with Add
and Remove
methods. In this way, you also don't need to specify ID
while adding new item to your list.
public class Movies
{
public List<Movie> List { get; set; }
public Movies()
{
List = new List<Movie>();
}
public void Add(Movie newMovie)
{
newMovie.Id = List.Count > 0 ? List.Max(x => x.Id)+1 : 1;
List.Add(newMovie);
}
public void Remove(Movie oldMovie)
{
List.Remove(oldMovie);
List.ForEach((x) => { if (x.Id > oldMovie.Id) x.Id = x.Id - 1; });
}
}
And for testing purposes:
Movies movies = new Movies();
movies.Add(new Movie() { Director = "first", Title = "first" });
movies.Add(new Movie() { Director = "second", Title = "second" });
movies.Add(new Movie() { Director = "third", Title = "third" });
movies.Add(new Movie() { Director = "fourth", Title = "fourth" });
movies.Add(new Movie() { Director = "fifth", Title = "fifth" });
movies.Remove(movies.List[3]);
user2915962
Updated on July 25, 2022Comments
-
user2915962 almost 2 years
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?