本文介绍了我如何通过设置参数Func键LINQ投影的SelectMany?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从集合返回属性值列表的功能:

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

我想有一个仿制版本,这将让我确定哪个领域,我想预测 - 而不是说的SpeakerName我想允许选择Video.Length或Video.Type

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.

我明白的SelectMany需要一个Func键,有啥使Func键可设置成允许把它当作参数传入这个函数的最好方法是什么?

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?

推荐答案

添加功能作为参数传递给方法

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

这篇关于我如何通过设置参数Func键LINQ投影的SelectMany?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:35