Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi people, I want to find out on how I can add a limit to the List<>.
What I want to do is have a limited List<employee> that can be inside a Class Team.

class Team
{
    public virtual String Name { get; set; }
    [Display(Name = "Project Title")]
    public String ProjectTitle { get; set; }
    public List<Employee> Employees { get; set; }
    public DateTime DateCreated { get; set; }
}



So each Team can have a maximum of lets say 8 people. How can I set a limit/constraint to a List<> on how many Employees can be added to one team? Maybe there are multiple ways of doing it, suggest the most effective way.
These entities will be tables in the data base, just to mention.
Posted

I'd simply have my 'Team class inherit from List<Employee> and define my own handler for the 'Add method for the List:
C#
public class Team : List<employee>
{
    public int MaxEmployees { get; private set; }

    public virtual String Name { get; private set; }

    [Display(Name = "Project Title")]
    public String ProjectTitle { get; private set; }

    public DateTime DateCreated { get; private set; }

    public Team(string name, string title, int maxEmployees)
    {
        Name = name;
        ProjectTitle = title;
        DateCreated = DateTime.Now;
        MaxEmployees = maxEmployees;    
    }

    // note use of 'new, not 'override ...
    public new void Add(Employee employee)
    {
        if (this.Count == MaxEmployees)
        {
            throw new ArgumentOutOfRangeException("", "Maximum Number of Employees on Team reached");
        }

        base.Add(employee);
    }
}</employee>
 
Share this answer
 
Comments
Maciej Los 15-Mar-15 6:09am    
5ed! Looks promissing ;)
BillWoodruff 15-Mar-15 7:27am    
Thank you, Maciej. Wonder why this one got a down-vote.
Maciej Los 15-Mar-15 7:35am    
Bill, i have no idea. The most of MVP's are an object of downvoting.
[no name] 15-Mar-15 20:28pm    
+5! ;-)
I would suggest an InvalidOperationException (or a custom one) though.
- Sebastian
Check this link
Provides solution using data annotations

http://stackoverflow.com/questions/5146732/viewmodel-validation-for-a-list[^]
 
Share this answer
 
Comments
Maciej Los 15-Mar-15 6:11am    
Although related link does not provide functionality to set maximum number of objects in a collection, but it shows a way to achieve that. +5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900