计算数组中匹配的值

时间:2013-12-04 14:29:59

标签: c#

好的,我正在查看某个值的文档,如果它们匹配此数组中的值,那么我想增加该特定值的计数。我这样做了:

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

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

但似乎必须有更好/更简单的方法。也许是一系列元组?我只是不知道。我知道这是一个非常简单的问题,我只是想不出如何用两个字符串来比较1和int计数。谢谢!

5 个答案:

答案 0 :(得分:1)

使用Dictionary<TKey, TValue> Class

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

稍后您可以在Dictionary.Keys中搜索该单词并递增计数器。

答案 1 :(得分:1)

Dictionary<string, int>怎么样?

答案 2 :(得分:0)

使用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);
    }
}

答案 3 :(得分:0)

您可以使用字典:

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

之后,您可以使用dicObj.ContainsKey搜索此中的特定单词,然后执行业务逻辑。

答案 4 :(得分:0)

我会使用Dictionary<string, int>,因为它非常有效:

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);
    }
}

现在您可以这样使用它:

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

将复杂性封装在方法中总是好的。这使代码更具可读性和安全性。

我使用Nullable<int>来处理名称是新的情况。

相关问题