列表中的字符串比较

时间:2015-02-18 08:46:28

标签: c# .net

我有两个包含字符串的列表

l1 = {abc;xyz}  
l2 = {lmn,xyz,abc}  

我想迭代这两个列表,看看l2是否包含l1中的所有元素,以及l1是否包含l2中的所有元素。
字符串的顺序无关紧要。请注意,字符串具有分隔符&#34 ;;"
我正在使用这两个for循环,但第二个for循环使索引超出范围。有更好的方法吗?

for (int i = 0; i < l1.Count; i++)
{
     if (l1[i].Contains(l2[i])) {
          Console.WriteLine("value {0} present in l1", l2[i]);
     }
     else {
          Console.WriteLine("value {0} is not present in l1", l2[i]);
     }
}

for (int i = 0; i < l2.Count; i++)
{
    if (l2[i].Contains(l1[i]))  {
        Console.WriteLine("value {0} present in l2", l2[i]);
    }
    else {
        Console.WriteLine("value {0} is not present in l2", l2[i]);
    }
}

3 个答案:

答案 0 :(得分:6)

您可以使用LINQ中的All方法:

// check whether l2 contains all elements of l1
l1.All(l2.Contains)
// check whether l1 contains all elements of l2
l2.All(l1.Contains)

答案 1 :(得分:0)

linq的解决方案更好(@ Selman22回答),你的问题在于检查你想要获得的列表数量:

     for (int i = 0; i < l1.Count; i++)
        {
            if (i < l2.Count)
            {
                if (l1[i].Contains(l2[i]))
                {
                    Console.WriteLine("value {0} present in l1", l2[i]);
                }
                else
                {
                    Console.WriteLine("value {0} is not present in l1", l2[i]);
                }
            }
        }

        for (int i = 0; i < l2.Count; i++)
        {
            if (i < l1.Count)
            {
                if (l2[i].Contains(l1[i]))
                {
                    Console.WriteLine("value {0} present in l2", l2[i]);
                }
                else
                {
                    Console.WriteLine("value {0} is not present in l2", l2[i]);
                }
            }
        }
    }

答案 2 :(得分:0)

另外,你应该在你的循环中删除第一个[]

    for (int i = 0; i < l2.Count; i++)
    {
         if (l1.Contains(l2[i])) {
              Console.WriteLine("value {0} present in l1", l2[i]);
         }
         else {
              Console.WriteLine("value {0} is not present in l1", l2[i]);
         }
    }

    for (int i = 0; i < l1.Count; i++)
    {
        if (l2.Contains(l1[i]))  {
            Console.WriteLine("value {0} present in l2", l2[i]);
        }
        else {
            Console.WriteLine("value {0} is not present in l2", l2[i]);
        }
    }