In my project, my data layer keeps a number of List collections to store the last returned data from SQl DB searches. I find myself repeating a lot of code. One in particular is used to see if a data object is already in the database, so that it can be updated instead of added. Here is an example:
public List<ClassA> ListClassA;
public List<ClassB> ListClassB;
public override bool ContainsClassA(ClassA group)
{
if (null == group)
{
throw new ArgumentNullException();
}
return ListClassA.Where(x => x.ClassA_ID == group.ClassA_ID).ToList().Count > 0;
}
public override bool ContainsClassB(ClassB group)
{
if (null == group)
{
throw new ArgumentNullException();
}
return ListClassB.Where(x => x.ClassB_ID == group.ClassB_ID).ToList().Count > 0;
}
Is there a way in which I can do this using the one function and Generics?
Would I need to rename the index fields so that they match e.g. ClassA_ID and ClassB_ID to ID?
Have both classes implement an interface with an ID property, and then use a generic with a constraint (
where T : [your interface name]).Also,
is a bit redundant, you could just use