是否有相当于批量包含?

时间:2013-01-28 02:04:16

标签: c# linq

是否有一些实用程序来检查序列是否包含多个元素而不是反复使用Contains

List<string> containter = new List<string>();

for (int i = 0; i < 10; i++)
{
    containter.Add("string #" + i);
}

if (containter.Contains("string #2") &&       //Is it possible to replace this with one call passing two strings to improve efficiency 
    containter.Contains("string #6"))
{
    //Do Something
}

3 个答案:

答案 0 :(得分:3)

根据更新的问题,我修改了我的答案:

List<string> containter = new List<string>();
for (int i = 0; i < 10; i++)
{
    containter.Add("string #" + i);
}
//define a checklist
List<string> checkList = new List<string> { "string #2", "string #6" };
//we're in, if every item in checkList is present in container
if (!checkList.Except(containter).Any())
{
    Console.WriteLine("true");
}

仍然可以使用Any。但在这种情况下,使用Except方法会很好。

如果checkList中的每个项目都出现在container中,则生成的序列中不包含任何元素,因此Any应该返回false

答案 1 :(得分:2)

我假设您想要比较两个序列,并想知道一个序列是否包含另一个序列中的所有元素。

var outer = new List<String>() { "1", "2", "3" };
var inner = new List<String>() { "1", "2" };
bool outerContainsAllInnerElements = inner.TrueForAll(i => outer.Contains(i));

或者,你可以使用Intersect(),但是当你试图计算它时,它会将你的项目投射到一个新的序列中。如果这就是你想要的,那很好,但是如果你不需要知道哪些元素相交,那么TrueForAll()将节省开销。

var outer = new List<String>() { "1", "2", "3" };
var inner = new List<String>() { "1", "2" };
var elementsInBoth = outer.Intersect(inner);
bool outerContainsAllInnerElements = (elementsInBoth.Count() == inner.Count());

答案 2 :(得分:1)

Any

string s = "I am a string";
string[] check = { "is", "my" };

Console.WriteLine(check.Any(x => s.Contains(x))); // False

s = "This is a string";
Console.WriteLine(check.Any(x => s.Contains(x))); // True

s = "my string";
Console.WriteLine(check.Any(x => s.Contains(x))); // True
相关问题