c# - 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();
我不知道如何使这项工作,所以任何帮助将不胜感激!
提前致谢!
解决方案
您可以使用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");
推荐阅读
- python - 在 Xlwings 中更改相同的字体颜色值
- php - Google Drive : 文件上传和访问文件
- java - 无法在将类导入 jar 的方法中运行 javac
- javascript - 如何在跳过周末 d3.js 时在 X 轴上绘制日期?
- javascript - Discord Oauth2 PassportJS 范围无效
- javascript - 几次点击后按钮消失
- reactjs - 将常规 HTML 元素转换为 Kotlin JS ReactElement
- c# - .NET Core 数据保护 - 它在哪里使用?
- cmake - 共享库、vcpkg、cmake 和链接
- flutter - flutter build appbundle eoor 消息:Gradle build 无法生成 .aab 文件。这个文件很可能是在下面生成的