How can I set LINQ SelectMany projection via Func parameter?

2.5k views Asked by At

I have a function which returns a list of property values from a collection:

    public static List<string> GetSpeakerList()
    {
        var Videos = QueryVideos(HttpContext.Current);
        return Videos.Where(v => v.Type == "exampleType"
            .SelectMany(v => v.SpeakerName)
            .Distinct()
            .OrderBy(s => s)
            .ToList();
    }

I'd like to have a generic version which will let me determine which field I'd like projected - say instead of SpeakerName I'd like to allow selecting Video.Length or Video.Type.

I understand that SelectMany takes a Func, so what's the best way to make the Func configurable to allow passing it as a parameter into this function?

1

There are 1 answers

3
tvanfosson On BEST ANSWER

Add the function as a parameter to the method.

public static List<string> GetVideosAttribute( Func<Video,string> selector )
{
    var Videos = QueryVideos(HttpContext.Current);
    return Videos.Where(v => v.Type == "exampleType"
                 .Select( selector )
                 .Distinct()
                 .OrderBy(s => s)
                 .ToList();
}


var speakers = GetVideosAttribute( v => v->SpeakerName );
var topics = GetVideosAttribute( v => v->Topic );