开发者

How to add collections together that implement a common interface

开发者 https://www.devze.com 2023-04-12 06:53 出处:网络
I have setup my classes as below. So both collections implement a common interface - IChild. Is there a way for a method on the parent to return the common parts of each collection please?

I have setup my classes as below. So both collections implement a common interface - IChild.

Is there a way for a method on the parent to return the common parts of each collection please?

I am using "+" below, and I know this doesn't work, but it indicates what I am trying to do.

public interface IChild
{
    DateTime Date { get; }
    Parent Parent { get; set; }
}

public class Boy : IChild
{
    public virtual Parent Paren开发者_如何转开发t { get; set; }
    public virtual DateTime GraduationDate { get; set; }
    public virtual DateTime Date { get { return ProcedureDate; } }
}

public class Girl : IChild
{
    public virtual Parent Parent { get; set; }
    public virtual DateTime WeddingDate { get; set; }
    public virtual DateTime Date { get { return ContactDate; } }
}


public Parent
{
    protected IList<Boy> _boys = new List<Boy>();
    protected IList<Girl> _girls = new List<Girl>();

    public virtual IEnumerable<Boy> Boys
    {
        get { return _boys; }
    }

    public virtual IEnumerable<Girl> Girls
    {
        get { return _girls; }
    }

    public virtual IEnumerable<IChild> Children
    {
        get
        {
            return _boys + _girls;
        }
    }
}

Thanks


public virtual IEnumerable<IChild> Children
{
    get
    {
        return _boys.Concat<IChild>(_girls);
    }
}


You can use Cast<T> to cast to the interface and then Concat to stream one sequence after the other.

return _boys.Cast<IChild>().Concat(_girls.Cast<IChild>()); // .NET 3.5 and greater

Note: If you are using .NET 3.5 you would need to perform the cast as shown here. If you are on .NET 4, you can follow Kristian Fenn's answer and omit the cast in lieu of .Concat<IChild>, which works because they made IEnumerable<T> covariant in the .NET 4 release, which allows IEnumerable<Boy> to be substituted when methods call for IEnumerable<IChild>.

return _boys.Concat<IChild>(_girls); // .NET 4.0 and greater

For completion, if you still happen to be using .NET 2.0, neither approach applies, although it's trivial to implement yourself.

public virtual IEnumerable<IChild> Children // .NET 2.0 and greater
{
    get
    {
        foreach (IChild boy in _boys)
            yield return boy;
        foreach (IChild girl in _girls)
            yield return girl;
    }
}


do you want common elements only, in resulting collection?

you can consider overloading + operator


public virtual IEnumerable<IChild> Children 
    { 
        get 
        { 
          List<IChild> list = new List<IChild>();
          list.AddRange(Boys);
          list.AddRange(Girls);  
          return list; 
        } 
    } 
0

精彩评论

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