List.Contains()未检测到字符串 [英] List.Contains() doesn't detects a string
问题描述
正如标题所述,我的列表"Cvqt"包含不同的字符串,例如"1 maxHearts Player"
,并且我试图检查它是否包含" maxHearths " + name
(每当输入方法为Player时它已经设置),并且我尝试了到那里但到了断点,它显示了Player,所以这不是问题,但是它将仅跳过if语句..这是代码
As the title says my list "Cvqt" contains different strings for example "1 maxHearts Player"
and I'm trying to check if it contains " maxHearths " + name
(which is already set whenever something enter's the method as Player) and i have tried to but break point there and it show's Player so this is not problem but it will simply jump over the if statement's.. Here's the code
if (Cvqt.Contains(" maxClubs " + name))
{
Cvqt.Remove(maxClubs.ToString() + " maxClub " + name);
}
else
{
maxClubs = j;
Cvqt.Add(maxClubs + " maxClubs " + name);
}
if (Cvqt.Contains(" clubs " + name))
{
Cvqt.Remove(clubs.ToString() + " clubs " + name);
clubs--;
}
else
{
Cvqt.Add(clubs + " clubs " + name);
}
推荐答案
在List<string>
上执行Contains
时,它仅检查列表是否包含与 完全匹配的字符串 传递给您的内容,不会部分匹配.
When you do Contains
on a List<string>
it only checks if the list contains a string that is a exact match to what you are passing in, it will not do a partial match.
如果要进行部分匹配,则需要做一些更复杂的操作,例如
If you want partial matches you need to do something more complicated like
if (Cvqt.Any(x=>x.Contains(" maxClubs " + name)))
{
Cvqt.Remove(maxClubs.ToString() + " maxClub " + name);
}
或
var item = Cvqt.FirstOrDefault(x => x.Contains(" maxClubs " + name));
if (item != null)
{
Cvqt.Remove(item);
}
如果要使用maxClubs
删除找到的项目而不是特定的字符串.
if you want to remove the found item instead of the specific string using maxClubs
.
这两种方法的作用是调用 List<T>.Contains(T t1)
均与执行Object.Equals(T t1, T listItem)
相同.
What those two methods do is call String.Contains
on each item instead of List<T>.Contains
on the entire list, which is what you where doing. Doing a List<T>.Contains(T t1)
is the same as doing a Object.Equals(T t1, T listItem)
on each item in the list.
这篇关于List.Contains()未检测到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!