Seems, you don't understand what OriginalGriff has already told you... So, i'll try to show you an example.
Imagine, you have a
Person
class:
public class Person
{
private string personname = string.Empty;
private DateTime dob = new DateTime(1900,1,1);
public Person(){}
public Person(string _name, DateTime _dob)
{
personname = _name;
dob = _dob;
}
public string Name
{
get => personname;
set => personname = value;
}
public DateTime DateOfBorn
{
get => dob;
set => dob = value;
}
public int Age => DateTime.Today.Year - this.dob.Year;
}
Now, you want to create "restricted-collection/list" of
Person
s. So:
public class RestrictedCollection
{
private List<Person> persons = null;
public RestrictedCollection()
{
persons = new List<Person>()
{
new Person("Adam", new DateTime(1984,1,1)), new Person("Bart", new DateTime(1972,10,11)),
new Person("Celine", new DateTime(1983,12,13)), new Person("Dijon", new DateTime(1986,3,17)),
new Person("Eveline", new DateTime(1979,9,1)), new Person("Elisabeth", new DateTime(1985,5,21)),
new Person("Ferdinand", new DateTime(1978,11,1)), new Person("Friderik", new DateTime(1979,7,31))
};
}
public void Add(Person p)
{
if(!persons.Contains(p))
persons.Add(p);
else
throw new InvalidOperationException($"'{p.Name}' born at {p.DateOfBorn.ToString("yyyy-MM-dd")} already exists!");
}
public void Remove(Person p)
{
if(persons.Contains(p))
persons.Remove(p);
else
throw new InvalidOperationException($"'{p.Name}' born at {p.DateOfBorn.ToString("yyyy-MM-dd")} does not exist!");
}
public List<Person> Filter(Func<Person, bool> predicate)
{
List<Person> filtered = persons.Where(predicate).ToList();
return filtered;
}
}
Finally, the usage:
void Main()
{
RestrictedCollection rc = new RestrictedCollection();
var result = rc.Filter(x=>x.Name.StartsWith("F"));
Person p = new Person("Maciej", new DateTime(1969, 12, 6));
rc.Add(p);
result = rc.Filter(x=>x.Name==p.Name);
rc.Add(p);
}
Note: in above example
Filter
method acts like a
Where
generic extension of
List<T>
.