1

As the title reads, is there a way using the ReSharper search pattern to find all instances of .First() that contains a condition, ignoring .First()?

The motivation for this search is in response to question
Why is LINQ .Where(predicate).First() faster than .First(predicate)?

We would like to see how many times we're using First() with a condition. The search will be extended to look for .FirstOrDefault().

Community
  • 1
  • 1
paligap
  • 942
  • 1
  • 12
  • 28
  • 1
    You will probably spend more time searching for instances of `First` with a predicate than the running time of such calls added together. Are you that worried about such a micro-optimization? –  Jul 05 '13 at 03:04
  • An ~30% improvement is still an improvement. Especially when dealing with larger lists. Are you implying the search criteria can't be created? – paligap Jul 05 '13 at 03:12
  • He's not saying it's not an improvement, nor is he saying it can't be done. He's saying the time taken to change it will probably be greater than the time saved by changing it. 30% of something very small is something even smaller. Are you sure this is the biggest performance problem in your app? – AakashM Jul 05 '13 at 07:55
  • Using the information provided by Joe White the change to the code-base only took a matter of seconds. – paligap Jul 11 '13 at 07:51

2 Answers2

3

You create a pattern for this about the way you would expect. Go to ReSharper > Find > Search with Pattern, and enter this pattern:

$enumerable$.First($args$)

Then in the placeholders list on the right, create two placeholders:

  • Add Placeholder > Expression, and name it enumerable. Don't specify a type (I tried specifying the type as IEnumerable<out T> and descendants, but for some reason that failed to find any usages; but if you don't specify a type, it works).
  • Add Placeholder > Argument, name it args, check the box for "Limit minimal number of arguments", and leave the number set to 1.

I tested this, and it found list.First(i => i%2 == 0) but not list.First(), so seems like exactly what you're asking for.

Joe White
  • 94,807
  • 60
  • 220
  • 330
  • Great solution Joe and with ReSharper it was an easy process to implement the replace as well. Thanks. – paligap Jul 05 '13 at 03:59
1

You could just use VisualStudio Find and use the RegEx option

Something like: .First(\({.+}\));

enter image description here

And you can also use Find and Replace to change all your predicates to Where +First`

enter image description here

sa_ddam213
  • 42,848
  • 7
  • 101
  • 110