patterncsharpModerate
Inefficient code inside of getter?
Viewed 0 times
codegetterinefficientinside
Problem
I have two lists of the same type and I want to be able view a list of both lists:
I think it is very inefficient to keep creating a new list object each time I want to get
Any elegant solutions?
public List HeaderPages;
public List SurveyPages;
public IReadOnlyList AllPages
{
get
{
List allPages = new List();
allPages.AddRange(this.HeaderPages);
allPages.AddRange(this.SurveyPages);
return allPages;
}
}I think it is very inefficient to keep creating a new list object each time I want to get
AllPages, so I thought I could store a private allPages list. But then I thought if I am in the class, I would have to remember to use the public AllPages rather than the private allPages - which may not be up-to-date.Any elegant solutions?
Solution
If you want to keep the two lists (otherwise check Hackworth's answer), the best solution would be to use LINQ extensions
This way you do not create any unnecessary collections. It forces you to use
public IEnumerable AllPages
{
get
{
return HeaderPages.Concat(SurveyPages);
}
}This way you do not create any unnecessary collections. It forces you to use
IEnumerable though, but in my opinion it is a good thing.Code Snippets
public IEnumerable<Page> AllPages
{
get
{
return HeaderPages.Concat(SurveyPages);
}
}Context
StackExchange Code Review Q#45386, answer score: 16
Revisions (0)
No revisions yet.