HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Inefficient code inside of getter?

Submitted by: @import:stackexchange-codereview··
0
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:

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

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.