Question Add item to list and avoid adding same items in a row


New member
Sep 26, 2016
Programming Experience
Hello, sounds easy, but can't make it work.

I need a list, which allows duplicates but never one by one.

I have a variable, which value changes constantly. The Timer runs to retrieve its value every second to add it to list.
It happens that the variable doesn't change its value for time longer than one second and there appear two or more same values in a row.

I wrote it like this, to add the value only, if it differs from the last one:

if (myVariable != myList[myList.Count-1])

But it keeps adding all of the values.

I'm not sure, if the code is not correct or is it the variable contents changing too fast.
What is the data type of 'myVariable'? If it's a reference type then two instances may look the same but if they are not the same object then they will not be considered equal.

Also, while it's not necessarily more efficient to run, you may find it more intuitive to write 'myList.Last()' rather than 'myList[myList.Count - 1]'.
I think you are right about the reference type of data.

The variable represents the values being returned by some object's method.

Still, my point is to store these values to list without direct duplicates. How to achieve that?

If it's about using 'myList[myList.Count - 1]', I'll stay with it for now for some reason.
I think you are right about the reference type of data.

Am I right or am I not right? I asked what the data type is because I wanted to know what the data type is. You didn't actually answer the question. It doesn't matter where the data comes from. It matters whether it's a reference type, i.e. a class, or a value type, i.e. a structure or enum. Which is it?
Bear with me please. I'm still learning.

I misled you. The variable is a value type.
Last edited:
In that case, I can't see any reason why your code wouldn't work. You need to debug. Just reading the code - especially just a snippet of code - is often not enough. It doesn't tell you whether that snippet of code is even being executed, what path execution is taking or what data is in use. Debugging can tell you all of those things.
The strange part is that when I'm printing out each last value from the above 'if' condition - right after adding it to the list, only the correct values are printed.

Printing out either the list 'count' or its contents shows that the redundant values are also stored.

Well, I will be looking into it. Thank you for your time.


I Solved it. To let the 'if' expression 'Count - 1', it has been preceded by:

myList.Insert(0, zeroValue);

Everytime the whole code was being executed, the 'zeroValue' was being added to the list as a new element instead of being assigned to the '0' index.
The value is the same as one of the values held by 'myVariable', so it looked like being duplicated, while it wasn't.
Last edited:
Top Bottom