一聚教程网:一个值得你收藏的教程网站

热门教程

怎么判断string字符串存在string[]数组里面

时间:2022-06-25 03:08:02 编辑:袖梨 来源:一聚教程网

问题
从.NET Framework的Library中可以看到,Array有实作IList接口,所以Insus.NET想使用IList.Contains()方法来判断。需要使用命名空间: using System.Collections;。

 代码如下 复制代码


string a = "Q";
string[] F = { "A", "B", "C" };
bool exist = ((IList)F).Contains(a);

解决办法

Array继承了IEnumerable接口,就可以用Contains方法,这个方法是Enumerable类的,

 代码如下 复制代码
public static bool Contains(this IEnumerable source, TSource value)
{
ICollection is2 = source as ICollection;
if (is2 != null)
{
return is2.Contains(value);
}
return source.Contains(value, null);
}

这是这个方法的内部代码,用reflector看Enumerable类提供的方法.

热门栏目