Using a linq or lambda expression in C # returns a collection plus one value

I want to return the collection plus one value. I am currently 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
source share
2 answers

Instead, you can use the collection initializer instead:

 public List<ChargeDetail> ChargeBreakdown { get { return new List<ChargeDetail>(_chargeBreakdown) {PrimaryChargeDetail}; } } 
+3
source

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

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

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

+1
source

Source: https://habr.com/ru/post/1381867/


All Articles