tags:

views:

329

answers:

2

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?

+2  A: 

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 );
tvanfosson
I get the following error when I run that:Error 7 The type arguments for method 'System.Linq.Enumerable.SelectMany<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,System.Collections.Generic.IEnumerable<TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Jon Galloway
Actually I don't think you need SelectMany since you're not actually selecting a collection of Speaker Names, Types, or Length. You're only selecting a single property from each then doing a distinct on it. It should work if you change SelectMany to Select.
tvanfosson
To be more precise, you use SelectMany when you want to select a collection of elements from each element in the enumeration. Use Select when you want to select a single property from each element in the enumeration.
tvanfosson
A: 

Do you really need SelectMany?

From what I read of MSDN, it is used to flatten sequences into a sequence, which I cannot understand from your example.

I guess you need a Select instead.
Correct me, if I am wrong.

shahkalpesh
That's in the checked answer.
Robert Harvey
@Robert: I said that before @tvanfosson edited his post.
shahkalpesh
This isn't an answer it's a comment.
TreeUK
@TreeUK: Care to explain what that means?
shahkalpesh