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 Parent { 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
You can use
Cast<T>to cast to the interface and thenConcatto stream one sequence after the other.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 madeIEnumerable<T>covariant in the .NET 4 release, which allowsIEnumerable<Boy>to be substituted when methods call forIEnumerable<IChild>.For completion, if you still happen to be using .NET 2.0, neither approach applies, although it’s trivial to implement yourself.