如何在没有linq的情况下获取List <>中元素的计数

时间:2018-07-30 17:54:14

标签: c#

我想对数组中的元素进行计数,但不使用linq

示例:

string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";

var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);

然后 理想的结果是:cat = 2,dog = 1,horse = 1

5 个答案:

答案 0 :(得分:2)

这是我想到使用Dictionary<string, int>的一种方式:

public static Dictionary<string, int> GetObjectCount(List<string> items)
{
    // Dictionary object to return
    Dictionary<string, int> keysAndCount = new Dictionary<string, int>();

    // Iterate your string values
    foreach(string s in items)
    {
        // Check if dictionary contains the key, if so, add to count
        if (keysAndCount.ContainsKey(s))
        {
            keysAndCount[s]++;
        }
        else
        {
            // Add key to dictionary with initial count of 1
            keysAndCount.Add(s, 1);
        }
   }

   return keysAndCount;
}

然后将结果取回并打印到控制台:

Dictionary<string, int> dic = GetObjectCount(list);

//Print to Console
foreach(string s in dic.Keys)
{
   Console.WriteLine(s + " has a count of: " + dic[s]);
}

答案 1 :(得分:1)

我不确定您为什么要为此寻找较少的LINQ解决方案,因为它可以非常容易且高效地完成。我强烈建议您使用它,并按如下所示进行操作:

var _group = list.GroupBy(i => i);
string result = "";
foreach (var grp in _group)
   result += grp.Key + ": " + grp.Count() + Environment.NewLine;

MessageBox.Show(result);

否则,如果您确实无法使用LINQ,则可以按照以下方式进行操作:

Dictionary<string, int> listCount = new Dictionary<string, int>();
foreach (string item in list)
    if (!listCount.ContainsKey(item))
        listCount.Add(item, 1);
    else
        listCount[item]++;

string result2 = "";
foreach (KeyValuePair<string, int> item in listCount)
    result2 += item.Key + ": " + item.Value + Environment.NewLine;

MessageBox.Show(result2);

答案 2 :(得分:0)

您可以尝试以下方法:

public int countOccurances(List<string> inputList, string countFor)
{
    // Identifiers used are:
    int countSoFar = 0;

    // Go through your list to count
    foreach (string listItem in inputList) 
    {
       // Check your condition
       if (listItem == countFor) 
       {
           countSoFar++;
       }
    }

    // Return the results
    return countSoFar;
}

这将为您提供任何刺痛次数。与往常一样,有更好的方法,但这是一个好的开始。

或者如果您愿意:

public string countOccurances(List<string> inputList, string countFor)
{
    // Identifiers used are:
    int countSoFar = 0; 
    string result = countFor;

    // Go through your list to count
    foreach (string listItem in inputList) 
    {
       // Check your condition
       if (listItem == countFor) 
       {
           countSoFar++;
       }
    }

    // Return the results
    return countFor + " = " countSoFar;
}

或者更好的选择:

private static void CountOccurances(List<string> inputList, string countFor) 
{
    int result = 0;
    foreach (string s in inputList)
    {
        if (s == countFor)
        {
            result++;
        }
    }

    Console.WriteLine($"There are {result} occurrances of {countFor}.");
}

答案 3 :(得分:0)

您的问题的简单解决方案是foreach loop

string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
Console.WriteLine($"There are {GetCount(myStrings, "cat");} cats.");
static int GetCount(string[] strings, string searchTerm) {
    int result = 0;
    foreach (string s in strings)
        if (s == searchTerm)
            result++;

    return result;
}

Linq是在后台进行的。但是,除非这是为了优化大型列表或获得学习经验,否则Linq应该是您的首选,如果您知道如何使用它的话。它的存在使您的生活更轻松。

此方法的另一种实现是简化所需的调用次数,只需将输出写入方法中即可:

string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
CountTerms(myStrings, "cat", "dog");
Console.ReadKey();

static void CountTerms(string[] strings, params string[] terms) {

    foreach (string term in terms) {
        int result = 0;
        foreach (string s in strings)
            if (s == term)
                result++;

        Console.WriteLine($"There are {result} instances of {term}");
    }
}

话虽如此,我强烈推荐瑞安·威尔逊的答案。他的版本简化了手头的任务。他实施的唯一缺点是,如果您以List<string>.Count(c => c == "cat")的方式以单一方式实施此操作。

答案 4 :(得分:-1)

Linq可以简化开发人员的生活。无论如何,您都可以这样:

        string a = "cat";
        string b = "dog";
        string c = "cat";
        string d = "horse";

        var list = new List<string>();
        list.Add(a);
        list.Add(b);
        list.Add(c);
        list.Add(d);

        var result = GetCount(list);

        Console.WriteLine(result);
        Console.ReadLine();


 static string GetCount(List<string> obj)
        {
            string result = string.Empty;
            int cat = 0;
            int dog = 0;
            int horse = 0;

            foreach (var item in obj)
            {
                switch (item)
                {
                    case "dog":
                        dog++;
                        break;
                    case "cat":
                        cat++;
                        break;
                    case "horse":
                        horse++;
                        break;
                }
            }

            result = "cat = " + cat.ToString() + " dog = " + dog.ToString() + " horse = " + horse.ToString();

            return result;
        }