IList.Contains(字符串[])如何在C#中使用?

IList.Contains(字符串[])如何在C#中使用?,c#,linq,C#,Linq,我正在寻找一种使用字符串数组参数调用IList.Contains的快速方法 有没有办法做到这一点: val[] = {"first", "second"} var temp = from i in items where i.list.Contains(val) select i; 使用All如果所有列表项都应该在值中我在LINQ方面非常糟糕,所以我不打算解决这个问题 首先做一个包含列表并不是最快的事情。在列表上做LINQ并不能使它更快。您需要做的

我正在寻找一种使用字符串数组参数调用IList.Contains的快速方法

有没有办法做到这一点:

val[] = {"first", "second"}

var temp = from i in items
           where i.list.Contains(val)
           select i;

使用
All
如果所有列表项都应该在值中

我在LINQ方面非常糟糕,所以我不打算解决这个问题

首先做一个包含列表并不是最快的事情。在列表上做LINQ并不能使它更快。您需要做的是创建一个HashSet,然后执行一个Contains。如果您有两个列表,我会说创建两个哈希集并将它们相交


如果要检查
i.list
是否包含
“第一个”
“第二个”


如果要检查
i.list
是否同时包含
“第一个”
“第二个”


但是,如果性能至关重要(认为在一个循环中调用了数百个项目),则更适合使用
HashSet
交叉点。

不确定“包含”是什么意思,如果希望所有项目都匹配,@lazyberezovsky的答案应该是正确的

但是,如果您想超越IList.Contains以支持数组(或可枚举),可以执行以下操作:

    /// <summary>
    /// Return true if <paramref name="allItems"/>
    /// contains one or more <paramref name="candidates"/>
    /// </summary>
    public static bool Contains<T>(IList<T> allItems, IEnumerable<T> candidates)
    {
        if (null == allItems)
            return false;

        if (null == candidates)
            return false;

        return allItems.Any(i => candidates.Contains(i));
    }
//
///如果为,则返回true
///包含一个或多个
/// 
公共静态布尔包含(IList所有项、IEnumerable候选项)
{
if(null==allItems)
返回false;
if(null==候选)
返回false;
返回allItems.Any(i=>candidates.Contains(i));
}

下面是一个扩展方法,用于获取列表中是否存在数组中的任何项。这个函数返回一个类似于IList.Contains的
bool

public static class IListExtensions
{
    public static bool ContainsAny<T>(this IList<T> list, IEnumerable<T> enumerable)
    {
        foreach (var item in enumerable)
        {
            if (list.Contains(item))
                return true;
        }
        return false;
    }
}
公共静态类
{
公共静态bool ContainsAny(此IList列表,IEnumerable可枚举)
{
foreach(可枚举中的变量项)
{
if(列表包含(项目))
返回true;
}
返回false;
}
}
用法:

IList<int> a = // ...
string[] b = // ...

a.ContainsAny(b);
IList a=/。。。
字符串[]b=/。。。
a、 康萨尼(b);

您的意思是“包含两个”还是“包含任何”?任何语句的可能重复项正是我要寻找的。非常感谢。
    /// <summary>
    /// Return true if <paramref name="allItems"/>
    /// contains one or more <paramref name="candidates"/>
    /// </summary>
    public static bool Contains<T>(IList<T> allItems, IEnumerable<T> candidates)
    {
        if (null == allItems)
            return false;

        if (null == candidates)
            return false;

        return allItems.Any(i => candidates.Contains(i));
    }
public static class IListExtensions
{
    public static bool ContainsAny<T>(this IList<T> list, IEnumerable<T> enumerable)
    {
        foreach (var item in enumerable)
        {
            if (list.Contains(item))
                return true;
        }
        return false;
    }
}
IList<int> a = // ...
string[] b = // ...

a.ContainsAny(b);