Mr. Zex
Mr. Zex

Reputation: 11

Create array of unique values from variables

I have a variable called X of type UNIT. This variable updates every couple of milliseconds.

In C# windows forms app I need to store data of this variable. Let's say at the first pause it was = 5. I need to create a list and store 5 then it changes to 7 then store 7 but if goes back to 5 again, ignore 5 since its already contained in my list

Then I need to access these variables from the list.

Upvotes: 0

Views: 116

Answers (2)

user2526236
user2526236

Reputation: 1538

        List<int> numbers = new List<int>(); // this is the list 
        int[] numbersArray = new int[] { 99, 98, 92, 97, 95 }; // numbers array

        foreach (var num in numbersArray)
        {
            if (!numbers.Contains(num)) // Check if the number exists
            {
                numbers.Add(num);// this will only add if the number doesn't exist 
            }
        }

Upvotes: 0

jdphenix
jdphenix

Reputation: 15415

Use a set. The logic that ensures duplicates are not added is built-in.

var numbers = new HashSet<uint>();

numbers.Add(5); // Adds 5, returns true. 
numbers.Add(5); // Doesn't add anything, returns false.

Upvotes: 3

Related Questions