List.Contains()未检测到字符串 [英] List.Contains() doesn't detects a string

查看:193
本文介绍了List.Contains()未检测到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我的列表"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆