我试图找出数组中的特定单元格是否包含给定字符串的一部分。由于数组不使用 .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
?
例如,如果 typeName
是 Pork
,Any()
只会在 时返回
。您的意思可能恰恰相反: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/