Timotheus
Timotheus

Reputation: 198

Counting values matched in an array

Ok so, I am looking through a document for certain values, and if they match the values in this array, then I want to increase the count for that specific value. I did this:

public static class Hex
{
    //example only, not real code
    public static string[] name = {"aba", "bcd", "c"}; 

    public static int[] count = new int[name.Length];
}

But it seems like there must be a better/easier way. Maybe an array of tuple? I just don't know. I know its a pretty easy question, I just can't think of quite how to do it with both strings to compare in 1, and int count for them. Thanks!

Upvotes: 0

Views: 114

Answers (5)

Shekhar Patidar
Shekhar Patidar

Reputation: 1

You can use a dictionary as bellow:

Dictionary<string, int> dicObj = new Dictionary<string, int>();
dicObj.Add("abc", 0);
…

After that you can search for the particular word in this using dicObj.ContainsKey and you can perform your business logic.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

I would use a Dictionary<string, int> since it is very efficient:

public static class Hex
{
    static Hex()
    {
        _HexNameCounts = new Dictionary<string, int>() 
        {
            {"aba", 0}, {"bcd", 0}, {"c", 0}
        };

    }

    private static Dictionary<string, int> _HexNameCounts = null;

    public static int? GetHexNameCount(string name)
    {
        int count;
        if (_HexNameCounts.TryGetValue(name, out count))
            return count;
        return null;
    }

    public static void SetHexNameCount(string name, int count)
    {
        _HexNameCounts[name] = count;
    }

    public static void IncreaseHexNameCount(string name, int count = 1)
    {
        int c = GetHexNameCount(name) ?? 0;
        SetHexNameCount(name, c + count);
    }
}

Now you can use it in this way:

int? abaCount = Hex.GetHexNameCount("aba");  
// or
Hex.SetHexNameCount("c", 3);  
// or
Hex.IncreaseHexNameCount("foo", 10);

It's always good to encapsulate complexity in methods. That makes the code more readable and safer.

I have used a Nullable<int> to handle the case that the name is new.

Upvotes: 0

EkoostikMartin
EkoostikMartin

Reputation: 6911

Use a Dictionary:

Dictionary<string, int> matches = new Dictionary<string, int>();

foreach(var item in document)
{
    if(matches.ContainsKey(item.stringvalue))
    {
       matches[item.stringvalue] += 1;
    }
    else
    {
       matches.Add(item.stringvalue, 1);
    }
}

Upvotes: 0

redent84
redent84

Reputation: 19239

What about a Dictionary<string, int>?

Upvotes: 1

Habib
Habib

Reputation: 223247

use Dictionary<TKey, TValue> Class

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("aba", 0);
dictionary.Add("bcd", 0);
dictionary.Add("c", 0);

Later you can search for the word in Dictionary.Keys and increment the counter.

Upvotes: 1

Related Questions