c# - 在数组上使用 System.Linq 中的 .Any 查找字符串

标签 c# arrays string linq

我试图找出数组中的特定单元格是否包含给定字符串的一部分。由于数组不使用 .Contains,我使用的是 .Any,但我对 .Any 工作原理的理解似乎太模糊,无法正确理解。

public void ProcessCSV (string typeName) {

    for (int y = 0; y < CSVReader.grid.GetUpperBound(1); y++) {
        if (CSVReader.grid[0,y] != null) {
            if ((CSVReader.grid[0,y].Any(s => typeName.Contains(s)))) {
                  // (add it to a new list)

所以我正在输入“Pork”、“Farm”等字符串。有时它似乎工作得很好,例如如果 typeName 是“Farm”,我只会从包含 [0, y] 中的字符串的数组中取回行。但在其他时候,如果我使用 Farm、另一个字符串或随机乱码,它只会返回包含任何字符串的每一行。

当我以这种方式调用 .Any 时,实际上发生了什么?我可以使用其他替代方法吗?

最佳答案

你可能理解错了。

Any 将返回一个 bool 值,指示序列中的 any 元素是否满足条件。当您键入 Any(s => ...) 时,s 是要检查的序列中的元素。

所以当你输入:

.Any(s => typeName.Contains(s))

...你本质上是在问:

Is any element from the sequence contained in the string typeName?

例如,如果 typeNamePorkAny() 只会在 时返回 true “ pig 肉”。包含(“ork”)。您的意思可能恰恰相反:

.Any(s => s.Contains(typeName))

Does any element contain the string typeName?

因此 "Pork and beef".Contains("Pork") 返回 true


如果您想要满足条件的序列中的 first 元素(而不是 bool 真值),请使用 FirstOrDefault(或者,当您知道总有至少一个,你可以使用 First 代替)。例如:

.FirstOrDefault(s => typeName.Contains(s))

Return the first element from the sequence that is contained in the string typeName; or the default value when there is none.

或者,反过来(我仍然认为你的意思):

.FirstOrDefault(s => s.Contains(typeName))

Return the first element from the sequence that contains the string typeName; or the default value when there is none.

关于c# - 在数组上使用 System.Linq 中的 .Any 查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15214809/

相关文章:

arrays - 我如何确保用户不能重复输入?

string - Oracle 中的日期月份名称语言?

c# - Task.WaitAll 在 ASP.NET 中挂起多个等待任务

c# - 如何在同一站点的 ashx 和 aspx 文件中使用 await/async?

C# - 从数据库中检索数据并将其分配给变量

c - 在 C 中重新分配字符串数组?段错误

javascript - findIndex javascript 问题

c++字符串在打印时缩短了两倍

java - 循环列表以查找特定值

c# - 如何在不使用 Bitmap.MakeTransparent() 的情况下在 C# 中将图像设置为具有透明背景?