在二维列表中搜索另一个列表中的字符串

时间:2019-06-03 23:53:19

标签: c# list

我想检查一个列表中的值是否在第二个列表中。第二个列表是在类中定义的二维列表。

这是一些示例数据。

tagNoMatchList[0] = "</Configuration>"
tagNoMatchList[1] = "<SWCheck>"
tagNoMatchList[2] = "</SWCheck>"

tagNoMatchList2[0].col = "A29"
tagNoMatchList2[0].tag = "</Configuration>"
tagNoMatchList2[1].col = "A52"
tagNoMatchList2[1].tag = "</SWCheck>"


public class tagNoMatchClass
{
    public string tag { get; set; }
    public string col { get; set; }
}

var tagNoMatchList = new List<string>();
var tagNoMatchList2 = new List<tagNoMatchClass>();


tagNoMatchList2.Add(new tagNoMatchClass
{
    tag = formatTag,
    col = Globals.ConvertColumnNumberToName(Globals.HeaderColumns[Globals.COLUMN_FORMATTING_TAG]) + rowIdx.ToString(),
});

bool test = tagNoMatchList[formatTagError].Any(x => tagNoMatchList2.Any(y=>x.Equals(y.tag)));

在上面的代码中,test的值始终为false。在测试tagNoMatchList [0] == tagNoMatchList2 [0] .tag和tagNoMatchList [2] == tagNoMatchList2 [1] .tag

时,它应该为true

我尝试了各种事情,无法弄清楚我在做什么错。

谢谢你,杰德温。我的术语一定错了。我将tagNoMatchClass称为二维列表。它几乎可以工作,但不完全可以。以下代码为我提供了与我想要的完全相反的代码。

for (int formatTagError = 0; formatTagError < tagNoMatchList.Count; formatTagError++)
{
    if (tagNoMatchList2.Any(x => x.tag == tagNoMatchList[formatTagError])) 
    {
        // Do something
    }
}

我尝试了以下操作,但是if总是评估为true。关于Any语法,我有些不了解。

for (int formatTagError = 0; formatTagError < tagNoMatchList.Count; formatTagError++)
{
    if (tagNoMatchList2.Any(x => x.tag != tagNoMatchList[formatTagError])) 
    {
        // Do something
    }
}

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

    public class tagNoMatchClass
    {
        public string tag { get; set; }
        public string col { get; set; }
    }
    public class Test
    {
        List<string> tagNoMatchList = new List<string>();
        List<tagNoMatchClass> tagNoMatchList2;


        public Test()
        {
            tagNoMatchList2 = new List<tagNoMatchClass>();
            tagNoMatchList.Add("</Configuration>");
            tagNoMatchList.Add("<SWCheck>");
            tagNoMatchList.Add("</SWCheck>");

            tagNoMatchList2.Add(new tagNoMatchClass() {  col = "A29", tag = "</Configuration>"});
            tagNoMatchList2.Add(new tagNoMatchClass() {col = "A52", tag = "</SWCheck>"});

            bool test =   tagNoMatchList2.Any(x => x.tag == tagNoMatchList[0]);

        }
    }

答案 1 :(得分:0)

它是这样的:

for (int formatTagError = 0; formatTagError < tagNoMatchList.Count; formatTagError++)
{
    if (!tagNoMatchList2.Any(x => x.tag == tagNoMatchList[formatTagError]))
    {
        // Do something
    }
}

非常感谢您让我足够靠近其他地方。