简体   繁体   中英

Generic Types and LINQ

I write two public classes (test1, test2) with two fields, eg 'Name' and 'Surname'. Then, I would like to fill data from a database to this objects. My first try was:

public List<T> FillFromDB<T>()
{
   IQueryable<T> query =
      from tbl in _table
      select new T {Name=tbl.name, Surname=tbl.surname}
}

But T don't know the fields. What could I do? Thanks for your help.

You can create a common interface (or class) from which Test1 and Test2 would inherit from and then specify the necessary constraints on the type parameter of FillFromDb .

public interface IHasName
{
    public string Name { get; set; }
    public string Surname { get; set; }
}
public class Test1 : IHasName
{
    public string Name { get; set; }
    public string Surname { get; set; }
}
public class Test2 : IHasName
{
    public string Name { get; set; }
    public string Surname { get; set; }
}
public List<T> FillFromDB<T>()
    where T : new(), IHasName
{
   IQueryable<T> query =
      from tbl in _table
      select new T {Name=tbl.name, Surname=tbl.surname}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM