0

I have a foreach loop that loops through items in a collection. Is it possible to re-use properties of an element if that item already exists? For example:

foreach(example item in creditItems)
{
    item.Total += item.Quantity;
}

Let's assume there are 3 items in creditItems. The first item and the third item are the same, at least they are supposed to be. The problem is they are considered completely different items(and understandably so). The problem with this is when it loops through to the last item, item.Quantity doesn't add to the original item.Total because since it's considered a new item, total is 0 + item.Quantity. Is my logic just off?

Zhafur
  • 1,626
  • 1
  • 13
  • 31
  • I wouldn't think this is possible. I would probably use a separate variable to do the sum or maybe a linq statement – webdad3 Apr 16 '14 at 20:32
  • *item.Quantity doesn't add to the original item.Total because since it's considered a new item* - Then it *is* new, i.e., it is a different object. You should simply ensure up front that each item is logically unique if that is your requirement. Otherwise you end up adding special cases everywhere and your code becomes a mess. Enforce your invariants as early as possible. – Ed S. Apr 16 '14 at 20:33

2 Answers2

0

Your first and third items may be the same item, but they're not the same object. You probably have an item ID field that is the same.

If you don't want two items with the same ID to exist in the collection, make sure the collection doesn't have two items with the same ID. If you do want two items with the same ID, you should decide how to handle this case - do you update the first item? The second one? Both of them?

Decice what you want to do, and from there implementation is going to be more straightforward.

zmbq
  • 38,013
  • 14
  • 101
  • 171
0

If i undestand you correctly, you have 2 or more of the "same" item in a List, Array,... whatever.

Lets say the Item got an ID which determines its type e.g. 10 is a car, 11 is a truck... whaetever.

You can then use LINQ to group those items by this ID by doing this:

var itemsGroupedById = creditItems.GroupdBy(item=> item.ID);

foreach(var idGroup in itemsGroupedById)
{
    decimal total = idGroup.Sum(item => item.Quantity); // This sums up all quantities of the same ItemId
    foreach(var item in idGroup) 
        item.Total = total; // This makes sure all items of the same kind store the total
    Console.WriteLine("The total of item {0} is {1}", idGroup.Key, total);

}
CSharpie
  • 9,195
  • 4
  • 44
  • 71