Cornwell
Cornwell

Reputation: 3410

Counting 2 elements

The title is somewhat confusing, let me try to explain what I'm trying to do. I'm receiving 2 strings at the same time, they are connected to each other on each receive but may or may not be related to the next received data.

So, if I receive this combination:

ID24
PART2

I want to create a variable that will increment a counter on that combination, eg.:

ID24-PART2++ (1)

Then, on the next receive round, I could get this:

ID59
PART2

So I would increment that particular counter:

ID59-PART2++ (1)

To finalize, if I received again:

ID24
PART2

Then:

ID24-PART2++ (2)

Hope I explained myself well. Performance is important.

Maybe some sort of array:

data["ID24"]["PART2"]++;

?

Upvotes: 0

Views: 67

Answers (3)

Jacob Lambert
Jacob Lambert

Reputation: 7679

What I would do is add the two strings together, and add it to a dictionary as a string:

Dictionary<Tuple<string,string>,int> stringDict = new Dictionary<Tuple<string,string>,int>();

Then for each string pair that you recieve:

Tuple<string,string> stringTuple = new Tuple<string, string>(string1, string2); //string1 and string2 are the strings you recieve

if(stringDict.ContainsKey(stringTuple))
    stringDict[stringTuple]++;
else
    stringDict.Add(stringTuple, 0);

If you were wanting to iterate this through a foreach loop you would use similar to this:

foreach(KeyValuePair<Tuple<string, string>, int> kvp in stringDict)
{
    Tuple<string, string> keyTuple = kvp.Key;
    int tupleCount = kvp.Value;
}

Upvotes: 0

Christophe De Troyer
Christophe De Troyer

Reputation: 2922

A solution could be to use a hashmap. Take your two inputs, cast them to a string and then store them in the hashmap with the two inputs as a key and a counter as the value.

Upvotes: 0

Servy
Servy

Reputation: 203802

Have a dictionary that maps a pair of strings to an integer:

Dictionary<Tuple<string, string>, int> dictionary = ...

Upvotes: 2

Related Questions