Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a generic list equal another generic list

Tags:

c#

This is my set up,

class CostPeriodDto : IPeriodCalculation
{
    public decimal? a { get; set; }
    public decimal? b { get; set; }
    public decimal? c { get; set; }
    public decimal? d { get; set; }
}

interface IPeriodCalculation
{
    decimal? a { get; set; }
    decimal? b { get; set; }
}

class myDto
{
    public List<CostPeriodDto> costPeriodList{ get; set; }

    public List<IPeriodCalculation> periodCalcList
    {
        get
        {
            return this.costPeriodList;  // compile error   
        }
    }
}

What would be the best way of doing this?

like image 303
Simon Wright Avatar asked Feb 03 '10 04:02

Simon Wright


2 Answers

Use Cast<IPeriodCalculation>() :

public class CostPeriodDto : IPeriodCalculation
{
    public decimal? a { get; set; }
    public decimal? b { get; set; }
    public decimal? c { get; set; }
    public decimal? d { get; set; }
}

public interface IPeriodCalculation
{
    decimal? a { get; set; }
    decimal? b { get; set; }
}

public class myDto
{
    public List<CostPeriodDto> costPeriodList { get; set; }

    public List<IPeriodCalculation> periodCalcList
    {
        get
        {
            return this.costPeriodList.Cast<IPeriodCalculation>().ToList();         
        }
    }
}

I believe in C#4, if you were using something implementing IEnumerable<out T>, you could simply do it the way you wrote it, and it would be resolved using Covariance.

class myDto 
{ 
    public IEnumerable<CostPeriodDto> costPeriodList{ get; set; } 

    public IEnumerable<IPeriodCalculation> periodCalcList 
    { 
        get 
        { 
            return this.costPeriodList;  // wont give a compilation error    
        } 
    } 
} 
like image 147
Dynami Le Savard Avatar answered Oct 11 '22 19:10

Dynami Le Savard


Try return this.costPeriodList.Cast<IPeriodCalculation>().ToList().

like image 35
John Feminella Avatar answered Oct 11 '22 17:10

John Feminella