Home > Back-end >  C# linq / Lambda - Adding an item to a list that summarizes all the items in the list
C# linq / Lambda - Adding an item to a list that summarizes all the items in the list

Time:09-21

I have al list of Purches items

I want to add new item to my list, that sum all the items in my list

this is my code:

    public class Purches
    {
        public int Id { get; set; }
        public int Items { get; set; }
        public int TotalPrice { get; set; }
    }
 List<Purches> purchesList = new List<Purches>() {
        new Purches() {
            Id = 1,
            Items = 3,
            TotalPrice = 220
        },
        new Purches() {
            Id = 2,
            Items = 5,
            TotalPrice = 300
        }
   };
      

now, I want to add the list new item that sum the Items and the TotalPrice properties

the result will be something like that:

 List<Purches> purchesList = new List<Purches>() {
                new Purches() {
                    Id = 1,
                    Items = 3,
                    TotalPrice = 220
                },
                new Purches()
                {
                    Id = 2,
                    Items = 5,
                    TotalPrice = 300
                },
                new Purches()
                {
                    Id = 0,
                    Items = 8,
                    TotalPrice = 550
                }
            };

I have to do it via linq / Lambda in c#

CodePudding user response:

Purches totalSum = new Purches
{
    Id = 0,
    Items = purchesList.Sum(p => p.Items),
    TotalPrices = purchesList.Sum(p => p.TotalPrices)
};
// now add it to your list if desired

CodePudding user response:

I would not recommend adding a summary item of the same type. That is just likely to lead to confusion. A better solution would be to to use either a separate object for the total, or use different types with a shared interface, for example:

public class PurchaceSummary{
    public List<Purches> Purchases {get;}
    public TotalItemCount => Items.Sum(p => p.Items);
    public TotalPrice => Items.Sum(p => p.TotalPrices);
}

Or

public interface IPurchaseLineItem{
    public int Items { get;  }
    public int TotalPrice { get;  }
}
public interface Purchase : IPurchaseLineItem{
    public int Id { get; set; }
    public int Items { get; set; }
    public int TotalPrice { get; set; }
}
public interface PurchaseSummary : IPurchaseLineItem{
    public int Items { get; set; }
    public int TotalPrice { get; set; }
}
// Use the LINQ methods from the previous example to create your totals for the summary

In either case it should be immediately obvious for everyone what each value represents.

  • Related