C # LINQ - does filter pick null when used with a method group?

Today I wrote some code that takes a list of instances of class A and creates a list of instances of class B using a static factory method:

public abstract class B
{
    public static B CreateB(A a)
    {
        // return a new B instance or null if a B instance can't be created
    }
}

      

I needed to filter out zeros, so I used LINQ to do both:

var bList = aList.Select(a => B.CreateB(a)).Where(b => b != null).ToList();

      

The code works as expected, but I noticed that Resharper was suggesting, when calling CreateB, I must "convert to method group". I wondered what this means and found some interesting answers on this site. For example: What is a method group in C #? and Asad's comment on the verse answer here Filtering null values ​​in Select (.Select (x => transform (x)) maybe. Select (transform))

So, I changed my code to:

var bList = aList.Select(B.CreateB).Where(b => b != null).ToList();

      

This works as expected too, but now I'll get to my question. Resharper now tells me where the lambda expression can be removed because b! = Null is "always true".

I've played around and Resharper is correct, but why? Why is there a difference in the returned Select () collection when I use a method group? Why does the Select () function seem to filter out zeros from the collection when I use a group of methods?

+3


source to share


1 answer


Both aList.Select(a => B.CreateB(a)).Where(b => b != null).ToList();

both aList.Select(B.CreateB).Where(b => b != null).ToList();

use the same method overload Select

.

I tested it using LinqPad and got the following output:

LinqPad



So, it Select

doesn't filter anything. Which version of Resharper and VisualStudio are you using?

Latest ReSharper on VS2013 says nothing:

Latest ReSharper on VS2013

+2


source







All Articles