Jon Galloway
Jon Galloway

Reputation: 53155

How can I set LINQ SelectMany projection via Func parameter?

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?

Upvotes: 2

Views: 2611

Answers (1)

tvanfosson
tvanfosson

Reputation: 532595

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 );

Upvotes: 6

Related Questions