Let say I have 2 lists
public List<TypeA> TypeARecords {get; set;}
public List<TypeB> TypeBRecords {get; set;}
Both TypeA and TypeB implements same Interface (let say IBaseRecord)
Now I have a read only property that returns list of all records
public List<IBaseRecord> AllRecords
{
get
{
var allRecs = new List<IBaseRecord>();
foreach ( var rec in TypeARecords)
allRecs.Add(rec);
foreach ( var rec in TypeBRecords)
allRecs.Add(rec);
return allRecs;
}
}
This works but I am sure there is more effective or just smarter way to do same thing
Any ideas?
You can make an iterator that returns the items in the list:
This way you don’t have to create a new list with all the items, it will just read from the existing lists.
Edit:
As Stan R. suggested, you can use the ToList method to create a copy of the list:
This is a bit better than having a property that returns a new list, as the ownership of the list gets clearer. Also, a property should not do such heavy lifting as creating lists, at least not every time the property is read.