如何通过Func参数设置LINQ SelectMany投影?

Jon*_*way 2 c# linq

我有一个函数,它从集合中返回属性值列表:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

我想要一个通用版本,它可以让我确定我想要投影的哪个字段 - 而不是SpeakerName我想允许选择Video.Length或Video.Type.

我理解SelectMany采用Func,那么使Func可配置为允许将其作为参数传递给此函数的最佳方法是什么?

tva*_*son 6

将函数作为参数添加到方法中.

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 );
Run Code Online (Sandbox Code Playgroud)

  • 实际上我认为您不需要SelectMany,因为您实际上并没有选择扬声器名称,类型或长度的集合.您只是从每个属性中选择一个属性,然后对其进行区分.如果将SelectMany更改为Select,它应该可以工作. (2认同)