I had a loop like this:
this.results = new List<Tuple<int, IEnumerable<Thing>>>();
var utcNow = DateTime.UtcNow;
var resultsLocker = new object();
Parallel.ForEach(
this.dataHelper.GetActiveIds(),
id =>
{
var result = new Tuple<int, IEnumerable<Thing>>(
id,
this.dataHelper.GetThing(id, this.PossibleLastRunTime, utcNow));
lock (resultsLocker)
{
this.results.Add(result);
}
});
and, using this answer, translated to a more compact and understandable:
this.results = this.dataHelper.GetActiveIds()
.AsParallel()
.Select(id => new Tuple<int, IEnumerable<Thing>>(
id,
this.dataHelper.GetThing(id, this.PossibleLastRunTime, utcNow)))
.ToList();
Now I have a more complex nested loop as such:
var measuresLocker = new object();
var measures = new List<Tuple<int, object, object>>();
Parallel.ForEach(
this.results,
result =>
{
foreach (var measuredValue in result.Item2.Select(destination =>
new Tuple<int, object, object>(
result.Item1,
destination.Message,
destination.DestinationName)))
{
lock (measuresLocker)
{
measures.Add(measuredValue);
}
}
});
I want to do something similar, but I’m getting stuck with this code:
measures = this.results
.AsParallel()
.Select(result => result.Item2.Select(destination =>
new Tuple<int, object, object>(
result.Item1,
destination.Message,
destination.DestinationName)).ToList()).ToList();
I seem to be getting a list of lists and I simply want the one list as per my original code. Can this be done pretty succinctly using LINQ? And if so, how?
To flatten a list of lists into a single list, use SelectMany() instead of Select().