-3

What is the best practice way to use two clauses in LINQ Contains method..

Title is string

This is my If statement :

if (oWeb.ParentWeb.Title.Contains("Ricky") || oWeb.ParentWeb.Title.Contains("John"))

I need solution like this :

 if (oWeb.ParentWeb.Title.Contains("Ricky", "John"))
Gohyu
  • 468
  • 2
  • 10
  • 32

3 Answers3

3

Since Title is string this actually has nothing to do with LINQ as the used Contains method is an instance method of string.

Assuming you have more strings to check, you can do something like that:

var strings = new[] {"Ricky", "John"};
if (strings.Any(oWeb.ParentWeb.Title.Contains))
    // do something

But roryap's answer using a regex seems preferable (as long as the number of strings to check is not too big).

Community
  • 1
  • 1
René Vogt
  • 43,056
  • 14
  • 77
  • 99
2

I don't think LINQ is the best option for that. Why not use regular expressions?

Regex.IsMatch(oWeb.ParentWeb.Title, "ricky|john", RegexOptions.IgnoreCase);
rory.ap
  • 34,009
  • 10
  • 83
  • 174
  • Better idea than LINQ if the number of strings to check is not too big (don't know if OP may have more than "ricky" and "john"). – René Vogt Aug 10 '16 at 14:39
1

Contains takes only one parameter, so you cannot do it this way.

You can make an array of items, and check containment with it:

var titles = new[] {"Ricky", "John"};
if (titles.Any(t => oWeb.ParentWeb.Title.Contains(t))) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523