Generic List for two different List classes instead of List<dynamic>

时间:2016-09-14 06:42:16

标签: c# linq generics

I am querying two different views based on some condition and it returns the collection and after that am using the collection to do some operation.

List<dynamic> query = new List<dynamic>();
            if (source == 1)
            {
                query = this.db.table1.Where(x => x.DATA_SRC_ID == source || x.DATA_SRC_ID == 3).ToList<dynamic>();
            }
            else if (source == 2)
            {
                query = this.db.table2.Where(x =>  x.DATA_SRC_ID == 3).ToList<dynamic>();
            }

            var result = query.Where(x => x.client_id == clientId).ToList();

if the view "table1" contains huge records means, converting to list<dynamic> degrades the performance. is there any other better way to do this ?. like some generic object should return from both if and else then i can use later in next.

below db context (using DB first approach in entity framework)

 private entities db = new entities ();

views/tables

table1
table2

instead of List<dynamic> how to decorate the list for two different classes.

1 个答案:

答案 0 :(得分:4)

最天真的实现(不是最好的实现)是简单地将每个项目投射到所需的类中,使您的类型列表object

var list = new List<object>();
list.Add(newInstanceOfA);
list.Add(newInstanceOfB);

现在你必须区分当前元素的类型:

foreach(var element in list) 
{
    var b = element as B();
    if(b != null) 
    {
        // do something with b
    }
    else 
    {
        a = (A) element;        // may fail if more types are possible
        // do something wit a
    }
}

如果两个类都实现相同的公共接口,那就更好了:

interface IMyInterface 
{
    void DoSomething();
}
class A : IMyInterface {}
class B : IMyInterface {}

现在您可以轻松创建新列表:

var list = new List<IMyInterface>();
list.Add(newInstanceOfA);
list.Add(newInstanceOfB);

foreach(var element in list)
{
    element.DoSomething();
}

在您的示例中,您现在可以执行以下操作:

query = this.db.table1
    .Where(x => x.DNA_PGM_PRTN_ID == partitionId && (x.DATA_SRC_ID == source || x.DATA_SRC_ID == 3))
    .Cast<IMyInterface>().ToList();

或者

query = this.db.table2
    .Where(x => x.CLIENT_PGM_PRTN_ID == partitionId && (x.DATA_SRC_ID == source || x.DATA_SRC_ID == 3))
    .Cast<IMyInterface>().ToList();

repectivly。

编辑:要将字段抽象为一些常见形式,您必须使用从中继承的抽象类而不是使列表成为List<MyAbstractClass>的接口。