String 检查字符串以查看字符串数组中是否出现字符串
我有一个字符串的通用列表: List listOfString=新列表() 然后,我在此列表中添加4个字符串:String 检查字符串以查看字符串数组中是否出现字符串,string,generics,list,.net-2.0,String,Generics,List,.net 2.0,我有一个字符串的通用列表: List listOfString=新列表() 然后,我在此列表中添加4个字符串: listOfString .Add("test1"); listOfString .Add("test2"); listOfString .Add("test3"); listOfString .Add("test4"); 我想检查字符串变量是否包含字符串数组中的任何元素 我见过描述的“Any”方法,但它不是用C#编译的
listOfString .Add("test1");
listOfString .Add("test2");
listOfString .Add("test3");
listOfString .Add("test4");
我想检查字符串变量是否包含字符串数组中的任何元素
我见过描述的“Any”方法,但它不是用C#编译的,我可以只在for循环中编译吗
谢谢。我认为问题更多的是测试字符串是否包含数组的任何元素 在伪代码中应该是这样的(我对.Net不太熟悉)
函数StringContainsAny(字符串测试、列表测试)
{
foreach(测试中的字符串测试)
{
if(测试包含(测试))
{
回归试验;
}
}
返回null;
}
如果我正确理解您的问题,您需要:
public static bool ContainsAnyElement(IList<string> l, string input)
{
foreach (var s in l)
{
if (l.Contains(s))
return true;
}
return false;
}
// Usage
IList<string> l = new List<string>() { "a", "b", "c" };
string test = "my test string with aa bbb and cccc";
Console.WriteLine(ContainsAnyElement(l, test));
publicstaticboolcontainsanyelement(IListL,字符串输入)
{
foreach(l中的变量s)
{
如果(l.包含(s))
返回true;
}
返回false;
}
//用法
IList l=新列表({“a”、“b”、“c”});
string test=“带aa bbb和cccc的我的测试字符串”;
控制台写入线(ContainsAnyElement(l,test));
如果使用LINQ方法扩展(.net 3.5),则可以使用Any函数。
像这样:
var foobar = "foobar";
new[] {"foo", "bar"}.Any(foobar.Contains);
public static class Utilities
{
public delegate bool AnyPredicate<T>(T arg);
public static bool Any<TSource>(IEnumerable<TSource> source, AnyPredicate<TSource> predicate)
{
if (source == null)
{
throw new ArgumentException("source");
}
if (predicate == null)
{
throw new ArgumentException("predicate");
}
foreach (TSource local in source)
{
if (predicate(local))
{
return true;
}
}
return false;
}
}
但如果你解开任何一个,你会发现它只是一个循环
公共静态bo
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource local in source)
{
if (predicate(local))
{
return true;
}
}
return false;
}
我希望这会有所帮助。要使任何()正常工作,您需要.NET 3.5,并且您的项目必须引用System.Core.dll,并包含System.Linq命名空间,如所示。您能让您的问题更清楚一点吗?你能举例说明你在寻找什么吗?
public static class Utilities
{
public delegate bool AnyPredicate<T>(T arg);
public static bool Any<TSource>(IEnumerable<TSource> source, AnyPredicate<TSource> predicate)
{
if (source == null)
{
throw new ArgumentException("source");
}
if (predicate == null)
{
throw new ArgumentException("predicate");
}
foreach (TSource local in source)
{
if (predicate(local))
{
return true;
}
}
return false;
}
}
var foobarlist = new[]{"foo", "bar"};
var foobar = "foobar";
var containsfoobar = Utilities.Any(foobarlist, foobar.Contains);