Search code examples
c#genericsilist

generic list question


I have my objects like this.

public class BaseTable
{
    public int ID               { get; set; }
    public int ParentID         { get; set; }
    public string Description   { get; set; }
    public bool IsActive        { get; set; }    

}

public class CarFuelType : BaseTable
{

}

and a test class

public class Test
{
    public IList<CarFuelType> GetAllActiveFuelTypes()
    {
        var result = GetAllActiveData<CarFuelType>(LookUpTableConstants.CarFuelType);

        return result.Cast<CarFuelType>().ToList(); 
    }


    private IList<T> GetAllActiveData<T>(int filter)
    {
        var result = from c in _lookUpTableValuesRepository.GetAllRowsWhere(l => l.ParentID == filter && l.IsActive==true)
                     select new BaseTable{ ID = c.ID, Description = c.Description, ParentID = c.ParentID };
        return result.ToList() as IList<T>;
    }

}

but I am getting null result returned from GetAllActiveData method. Is there anyway I convert IList from one type to another.


Solution

  • You've got a problem here, because you're not actually creating any instances of the derived class. You need to actually create instances of CarFuelType rather than BaseTable. Once you've done that, you won't need any casting. You can do that in this way - at least for LINQ to Objects:

    private IList<T> GetAllActiveData<T>(int filter) where T : BaseTable, new()
    {
        var result = from c in _lookUpTableValuesRepository
                                   .GetAllRowsWhere(l => l.ParentID == filter 
                                                    && l.IsActive==true)
                     select new T() { ID = c.ID, 
                                      Description = c.Description,
                                      ParentID = c.ParentID };
        return result.ToList();
    }
    

    I doubt this will work for LINQ to SQL or the Entity Framework though... you'd probably have to create instances of BaseTable in the LINQ to SQL query, then convert them in memory, e.g.

        var baseQuery = from c in _lookUpTableValuesRepository
                                   .GetAllRowsWhere(l => l.ParentID == filter 
                                                    && l.IsActive==true)
                     select new BaseTable { ID = c.ID, 
                                            Description = c.Description,
                                            ParentID = c.ParentID };
    
        var converted = baseQuery.AsEnumerable()
                                 .Select(b => new T() { ID = b.ID, 
                                                        Description = b.Description,
                                                        ParentID = b.ParentID };
    

    That may lose the "entity-ness" however - you may have problems using those objects for updates etc.