Search code examples
c#generic-list

C# generic method for returning maxId


I would like to have a method that could perform this code on other objects I have (For example: prize, person, team and so on.), so I don't have to write the same code multiple times and just put let's say GetMaxId(List< Person > persons, Person person). Each of my objects has an Id property. I'm using this so when i save to text file through user input in my winform application, so i can generate the id that be 1 bigger based on the current number of eg Persons in the text file.

public static int GetMaxId(List<Prize> prizes, Prize prize)
    {
        int maxId = 1;
        if (prizes.Count > 0)
            maxId = prizes.Max(p => p.Id) + 1;

        prize.Id = maxId;
        return prize.Id;
    }

So, what i would like is in each of the classes, for example i want to return the id for the person when creating a new person but i don't want to modify the code from taking in parameters for Prize and having to change it to Person. i would like a method that takes generic parameters so when i call it in Person class, i can just pass the (list persons, Person person).

I don't know which type to pass in the original method so that i can reuse it in other classes.


Solution

  • Well, I think what you want is a generic function to retrieve the next id of a collection. You can try using generics.

    Something like this:

    public static int GetNextId<T>(List<T> items, Func<T,int> selector)
        {
            if (items.Count < 1)
                return 1;
    
            return items.Max(selector)+1;
        }
    

    And you use the function like this:

    public class Person
        {
            public int PersonID { get; set; }
        }
    
        public static void Test()
        {
            var persons = new List<Person>()
            {
                new Person() {PersonID=1 },
                new Person() {PersonID=2 },
    
            };
    
            var nextId = GetNextId(persons, i => i.PersonID);//returns 3
        }