![](/img/trans.png)
[英]Generic LINQ function - SelectMany with selection Func as a parameter
[英]How can I set LINQ SelectMany projection via Func parameter?
我有一個函數,該函數從集合中返回屬性值的列表:
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();
}
我想要一個通用版本,該版本可以讓我確定要投影的字段-例如,我希望允許選擇Video.Length或Video.Type而不是SpeakerName。
我知道SelectMany帶有Func,那么使Func可配置以允許將其作為參數傳遞給此函數的最佳方法是什么?
將函數作為參數添加到方法中。
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 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.