Reputation: 489
I have a long string S that may contain pattern p1, p2, p3, ....;
All patterns are put in a MatchCollection
object
I would like to do something like
string ret=p_n if !(S.Contains(p_n))
I write a for loop to do this
foreach(string p in PatternList)
{
s=(!S.contain(p.valus))?p.value:"";
}
I would like to know a LINQ statement to make my cocde more elgant.
Upvotes: 3
Views: 226
Reputation: 1062
static void Main(string[] args)
{
string S = "p1, p2, p3, p4, p5, p6";
List<string> PatternList = new List<string>();
PatternList.Add("p2");
PatternList.Add("p5");
PatternList.Add("p9");
foreach (string s in PatternList.Where(x => !S.Contains(x)))
{
Console.WriteLine(s);
}
Console.ReadKey();
}
Upvotes: 0
Reputation: 3371
class Program
{
static void Main(string[] args)
{
string S = "12345asdfasdf12w3e412354w12341523142341235123";
string patternString = "one1234554321asdf";
MatchCollection p_ns = Regex.Matches(patternString, "one|12345|54321|asdf");
var nonMatches = (from p_n in p_ns.Cast<Match>()
where !S.Contains(p_n.Value)
select p_n.Value);
foreach (string nonMatch in nonMatches)
{
Console.WriteLine(nonMatch);
}
Console.ReadKey();
}
}
Or to use Justin's method from his answer you could also use the below variation.
class Program
{
static void Main(string[] args)
{
string S = "12345asdfasdf12w3e412354w12341523142341235123";
string patternString = "one1234554321asdf";
MatchCollection p_ns = Regex.Matches(patternString, "one|12345|54321|asdf");
var nonMatches = p_ns.Cast<Match>().Where(s => !S.Contains(s.Value));
foreach (Match nonMatch in nonMatches)
{
Console.WriteLine(nonMatch.Value);
}
Console.ReadKey();
}
}
Upvotes: 0
Reputation: 245399
var patterns = new List<string> { "one", "two", "three" };
var misses = patterns.Where(s => !longString.Contains(s));
Upvotes: 4