tags:

views:

127

answers:

1

I have an collection of Videos who have a field typeidentifier that tells me if a video is a trailer, clip or interview.

I need to put them in 3 seperate collections.

var trailers = myMediaObject.Videos.Where(type => type.TypeIdentifier == 1);
var clips = myMediaObject.Videos.Where(type => type.TypeIdentifier == 2);
var interviews = myMediaObject.Videos.Where(type => type.TypeIdentifier == 3);

Is there a more efficient way of doing this? I love using Linq here though.

+6  A: 

How about:

var lookup = myMediaObject.Videos.ToLookup(type => type.TypeIdentifier);
var trailers = lookup[1];
var clips = lookup[2];
var interviews = lookup[3];

Note that this will materialize the results immediately, whereas your first version didn't. If you still want deferred execution, you might want to use GroupBy instead - although that will be slightly trickier later on. It really depends what you need to do with the results.

Jon Skeet
I don't need deferred execution today (that may change in the future, so thanks for the GroupBy).I wish I could do this var (trailers, clips, interviews) = myMediaObject.Videos.ToLookup(type => type.TypeIdentifier);
halivingston
I love `ToLookup`. Very overlooked method.
leppie
@halvingston: Is it *really* a problem to have four statements instead? Bear in mind that you'd need to be able to specify the 1, 2, 3 part somewhere too...
Jon Skeet
I suppose not, I was hoping GroupBy + some syntax sugary that only you know would be able to reduce this to one line or maybe two. I won't die without it.
halivingston
Also is this really more efficient?
halivingston
@halivingston: Well, it depends on what you're doing afterwards. It's only going through the original sequence once instead of three times, which is nice - but it's materializing the results straight away, which may or may not be as good.
Jon Skeet