3

I'd like to return a collection plus a single value. Presently I am using a field to create a new list adding a value to the list and then returning the result. Is there a way to do this with a linq or lambda expression?

private List<ChargeDetail> _chargeBreakdown
    = new List<ChargeDetail>();

public ChargeDetail PrimaryChargeDetail { get; set; }

public List<ChargeDetail> ChargeBreakdown
{
    get
    {
        List<ChargeDetail> result =
            new List<ChargeDetail>(_chargeBreakdown);
        result.Add(PrimaryChargeDetail);

        return result;
    }
}
3
  • You might want to return a collection other than List<T> - msdn.microsoft.com/en-us/library/ms182142%28VS.80%29.aspx Commented Apr 7, 2010 at 22:38
  • @Reed added the _chareBreakdown field Commented Apr 7, 2010 at 22:39
  • @Russ thank you for the suggestion, I won't for the production code. ;) Commented Apr 7, 2010 at 22:41

2 Answers 2

4

You could use a collection initializer syntax instead:

public List<ChargeDetail> ChargeBreakdown
{
    get
    {
        return new List<ChargeDetail>(_chargeBreakdown) {PrimaryChargeDetail};
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you change the property type to IEnumerable<ChargeDetail> you could do:

public IEnumerable<ChargeDetail> ChareBreakdown
{
    get { return _chargeBreakdown.Concat(new[] { PrimaryChargeDetail }); }
}

Which could be simpler depending on how clients use the class (for example if they just iterate through the collection). They could always call ToList if they need to manipulate a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.