3

I'm basically trying to convert this:

private int FindIndexOf(string valueOne, string valueTwo, List<string> list)
{
    return list.FindIndex(s =>
        s.ToLower().Contains(valueOne.ToLower()) &&
        s.ToLower().Contains(valueTwo.ToLower())
        );
}

to make use of params like this:

private int FindIndexOf(List<string> list, params string[] args)
{
    string pattern = String.Format("([{0}]+)", String.Join("]+[", args));
    Regex regEx = new Regex(pattern, RegexOptions.IgnoreCase);
    return list.FindIndex(s => regEx.IsMatch(s.ToLower()));
}

I'm not very good with RegEx and I can't think of a way to implement this in linq. Any suggestions?

DobleA
  • 334
  • 1
  • 3
  • 13

3 Answers3

3

You don't need regex and you don't need ToLower:

private int FindIndexOf(List<string> list, params string[] args)
{
    return list
       .FindIndex(s => args
           .All(str => s.IndexOf(str, StringComparison.OrdinalIgnoreCase) >= 0));
}

Why ToLower can be incorrect: https://stackoverflow.com/a/234751/284240

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Ah that makes sense. Thank you for the link on ToLower. I'll definitely stop using that in my code! – DobleA Dec 07 '13 at 00:11
1

Use All instead:

var argsLower = args.Select(q=> q.ToLower());
list.FindIndex(c => argsLower.All(x => c == x));
Jens Kloster
  • 11,099
  • 5
  • 40
  • 54
0

A regex-based solution, for the record:

private int FindIndexOf(List<string> list, params string[] args)
{
    string pattern = args.Aggregate(new StringBuilder(), 
        (sb, a) => sb.Append("(?=.*").Append(Regex.Escape(a)).Append(")")
    ).ToString();
    Regex regEx = new Regex(pattern, RegexOptions.IgnoreCase);
    return list.FindIndex(s => regEx.IsMatch(s));
}
pobrelkey
  • 5,853
  • 20
  • 29