-3

I'm checking if an object is already inside my list, this object has an property with a value in it. If the object is already in the list I would like to get the object back and add the values together and then put it back in the list.

Here is my code:

if (!uniqueList.Contains(element))
{
    uniqueList.Add(element);
}
else
{
    elementOld = uniqueList ??
    elementOld.value += element.value;
    uniqueList.add(elementOld);
}

I just need help with the two ?? in the code.

Jim
  • 2,974
  • 2
  • 19
  • 29
roy-willemse
  • 325
  • 1
  • 4
  • 14
  • What is the type of element? Can you post the class definition for it? Please add all the details. – Vinod Dec 13 '16 at 18:51
  • Actually if `element` is an object and `uniqueList.Contains(element)` is true, then `element` is already the same object as the one you have in the list, no need to get it. BUT if what you need is only to look for a specific property of that object, then `Contains` will not work for you and you should do something like `uniqueList.FirstOrDefault(x => x.Property == element.Property)` and then compare the result with `null`. Anyway, what are you trying to do? From your code it seems you want to increase the element's value and then **add it again to the list**. – Andrew Dec 13 '16 at 19:00
  • Is `value` the property that defines if the element is already in the list, or another one? If `elementOld` is the existing `element` in the list, then what you are doing is the same as `elementOld.value *= 2`. – Andrew Dec 13 '16 at 19:08
  • @Gameshadow, have you checked any of the comments and answers here? – Andrew Dec 27 '16 at 10:11
  • @Gameshadow, still there? – Andrew Jan 14 '17 at 02:10

1 Answers1

2

If you know the object is in the list, you can use IndexOf() to find the object's location in your list.

else
{
    int index = uniqueList.IndexOf(element);
    var myElement = uniqueList[index];
    //do whatever you want with it here, and you don't have to
    //put it back afterwards, it will still be in your list.
}

Edit: As Andrew pointed out, if you can find the index of the element in your list with the above code, you already have a reference to that item in the list. If you do not have a reference to the exact object in the list that you want to find, you will have to compare it's members to find a match instead because the code above will return -1 for the index.

Sam W
  • 599
  • 2
  • 16
  • 1
    But won't `myElement` be nothing more than another reference to the same object `element` already points to? As I commented above, if you already have `element`, you don't need to find it anywhere . But anyway I guess he doesn't have the exact instance (so `Contains` or `IndexOf` won't work). – Andrew Dec 14 '16 at 01:22
  • Right you are! I can't believe that I never realized that before.... I've updated my answer to include what you pointed out. Thanks! – Sam W Dec 14 '16 at 14:23