0

I have two enumerables that I would like to use with PLINQ, how do I combine them correctly? Here they are:

List<Message> messageList=...;

IEnumerable<int> lineNums=Enumerable.Range(1,messages.Count);
IEnumerable<Message> messages=messageList;

In a nutshell, I want to apply some complex time consuming formatting in parallel and map the line numbers to the messages. Here is what I mean (without the line numbers), since I do not know how to integrate them into this expression:

var formattedLine=messageList.AsParallel().AsOrdered().Select(message =>
  {
    ... // Some work here to be done in parallel
    return string.Format(...); // Some formatting here of message
  }

I will then use the results of the formatting with a simple foreach:

foreach (var line in formattedLine)
  ...

Well the above is good for the messages, but I want to include some formatted lineNums in there from the enumerable in a one-to-one correspondance with the messages. I can't just interlocked increment an integer in the lambda, because I will not get ordered results. So, basically I need a one-to-one mapping of the two enumerables as my params to the lambda, I suppose.

How do I do this?

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181

1 Answers1

4

Use the select overload that takes an item and the item's index, like this:

var formattedLine=messageList.AsParallel().AsOrdered().Select((message, index) =>
{
    ... // Some work here to be done in parallel
    return string.Format(...); // Some formatting here of message using index
});
svick
  • 236,525
  • 50
  • 385
  • 514
Kris Vandermotten
  • 10,111
  • 38
  • 49