首页 > 解决方案 > C#:使用LINQ计算另一个列表中的列表中字符串的出现次数?

问题描述

我正在尝试计算主列表中动态添加的列表中字符串的出现次数。这是主要列表:

public static List<string>[] tables = new List<string>[30];

这就是我向其中添加项目的方式:

public static int takenTablesDayTotal;

public static void AddProductToTable()
{
    int tableNum = int.Parse(Console.ReadLine());

    if (tableNum < 1 || tableNum > 30) { throw new Exception(); }

    choiceName = Console.ReadLine();

    if (tables[tableNum] is null)
    {
        tables[tableNum] = new List<string>();
        takenTablesDayTotal++;
    }

    tables[tableNum].Add(choiceName);
}

这就是我尝试进行计数的方式,但由于某种原因它似乎无法正常工作(从 1 开始,当检测到所需的字符串时停止计数)

salesProductDayTotal = tables.Where(s => s != null && s.Contains("string")).Count();

我不知道如何使这项工作,所以任何帮助将不胜感激!

提前致谢!

标签: c#listlinq

解决方案


您可以使用SelectMany来分隔两巢结构。然后用Count得到你想要的。

例如- 计算每日苹果销售数量

List<string>[] tables = new List<string>[30];
tables[0] = new List<string>{
    "Apple", "Banana", "Cherry"
};
tables[1] = new List<string>{
    "Peach", "Apple", "Watermelon"
};
tables[2] = new List<string>{
    "Mango", "Grape", "Apple"
};

//the daily sales count of Apple.
var dailyAppleSalesCount = tables.Where(x => x != null)
        .SelectMany(s => s).Count(x => x == "Apple");

推荐阅读