How to configure LINQ SelectMany function using Func parameter?

I have a function that 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 would like to have a general version that will allow me to determine in which field I would like to project - say instead of SpeakerName. I would like to allow the selection of Video.Length or Video.Type.

I understand that SelectMany accepts Func, so what's the best way to make Func customizable to pass it as a parameter to this function?

+1
source share
1 answer

Add a 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 ); 
+5
source

All Articles