tags:

views:

44

answers:

2

Hi,

I want to write a LINQ query which returns two streams of objects. In F# I would write a Seq expression which creates an IEnumerable of 2-tuples and then run Seq.unzip. What is the proper mechanism to do this in C# (on .NET 3.5)?

Cheers, Jurgen

+1  A: 

Your best bet is probably to create a Pair<T1, T2> type and return a sequence of that. (Or use an anonymous type to do the same thing.)

You can then "unzip" it with:

var firstElements = pairs.Select(pair => pair.First);
var secondElements = pairs.Select(pair => pair.Second);

It's probably worth materializing pairs first though (e.g. call ToList() at the end of your first query) to avoid evaluating the query twice.

Basically this is exactly the same as your F# approach, but with no built-in support.

Jon Skeet
+1  A: 

Due to the lack of tuples in C# you may create an anonymous type. Semantics for this are:

someEnumerable.Select( inst => new { AnonTypeFirstStream = inst.FieldA, AnonTypeSecondStream = inst.FieldB });

This way you're not bound in the amount of streams you return, you can just add a field to the anonymous type pretty like you can add an element to a tuple.

emaster70