开发者

Generics and multiple List<> searches

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开发者_Python百科.g. ClassA_ID and ClassB_ID to ID?


I would use a Dictionary instead of a List for caching:

 Dictionary<ClassA_ID, ClassA> classACache;
 ...
 classACache.ContainsKey(aitem.ClassA_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,

ListClassA.Where(x => x.ClassA_ID == group.ClassA_ID).ToList().Count > 0

is a bit redundant, you could just use

ListClassA.Any(x => x.ClassA_ID == group.ClassA_ID)


You can implement IEquatable<T> on your classes like this:

public class ClassA : IEquatable<ClassA>
{
    public int ID { get; set; }

    public bool Equals(ClassA other)
    {
        if (this.ID == other.ID)
            return true;

        return false;
    }
}

Then you can simply use the List<T>.Contains() method like this:

List<ClassA> ListOfClassA = new List<ClassA>();

ClassA ItemA = new ClassA() { ID = 1 };
ClassA ItemB = new ClassA() { ID = 2 };

ListOfClassA.Add(ItemA);

if (ListOfClassA.Contains(ItemA))
    Console.WriteLine("The list contains ItemA.");

if (ListOfClassA.Contains(ItemB))
    Console.WriteLine("The list contains ItemB.");

The output of the above code is:

The list contains ItemA.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜