3

Okay, I have this KeyValuePair list:

public ObservableCollection<KeyValuePair<string, float>> values { get; set; }

Now I want to know if there is already this element. I tried this with:

bool conaintsValue = values.Contains(value);

But how do I replace this element now? This is what I tried:

if(values.Contains(value))
{
    int i = values.IndexOf(value);
    values[i] = value;
}

But this does not work.

EDIT: I add a value like this! Values = List!

KeyValuePair<string, float> value = new KeyValuePair<string, float>(chartKey, chartValue);

This is my list:

public ObservableCollection<KeyValuePair<string, float>> values { get; set; }
Marstaw
  • 51
  • 1
  • 9
  • 4
    You replace the value with the same value. – daniel Mar 13 '17 at 11:04
  • 1
    Why are you trying to replace `value` with itself? Have you checked whether `values.Contains(value)` is returning `true` or not? – JLRishe Mar 13 '17 at 11:07
  • Because my program can Change the value `float`and the key `string` stays the same. And I want to Change this element at the same index. – Marstaw Mar 13 '17 at 11:09
  • Also, don't call `Contains` followed by `IndexOf` as they both have to scan the list. Just call `IndexOf` and if the return index is `-1` you know the item isn't in the list. – Sean Mar 13 '17 at 11:09
  • Would this not be easier with a Dictionary of some type? – ClickRick Mar 13 '17 at 11:11
  • @ClickRick I never used a Dictionary I just heared of it. If its not so much can you give me a Little Code and Explanation ? – Marstaw Mar 13 '17 at 11:15
  • http://stackoverflow.com/a/7914854/6071824 – Christopher Lake Mar 13 '17 at 11:19
  • @ChristopherLake thank you! – Marstaw Mar 13 '17 at 11:22
  • You can use Dictionary instead of ObservableCollection> but you will loose the specific features of ObservableCollection. Maybe you use it in a WPF binding. – daniel Mar 13 '17 at 12:02
  • I'm using this in a WPF Toolkit chart. So I Need a list that updates itself. Don't know if this still working with Dictonary – Marstaw Mar 13 '17 at 12:09

1 Answers1

4

I tried this:

if (values.Contains(value))
{
    int i = values.IndexOf(value);
    KeyValuePair<string, float> newValue = new KeyValuePair<string, float>("test", (float)11.3);
    values[i] = newValue;
}

and it works. You should replace the old value with a new one not with the same value.

daniel
  • 132
  • 7
  • That answered this question. Now I have a different Problem but its not about this :) Thank you! – Marstaw Mar 13 '17 at 11:29