Reputation: 51
I have a set of data that requires some processing but I want to split the work available threads. How can I change this into a single instruction, preferably removing the for-loop?
string[] keysForThread;
IEnumerable<string> allData;
List<string> dataForSingleThreadToProcess;
for (int i = 0; i < keys.length; i++)
dataForSingleThreadToProcess.AddRange(allData.Where(x => x.StartsWith(keys[i])));
I don't mind changing the string[] keysForThread into a List and/or the List dataForSingleThreadToProcessinto an IEnumerable.
Upvotes: 0
Views: 105
Reputation: 4532
This should do the job:
dataForSingleThreadToProcess = allData.Where(x => keys.Any(x.StartsWith)).ToList();
Upvotes: 0
Reputation: 50104
This is a direct way of doing what your code does without the for loop.
var data = keys.SelectMany(k => allData.Where(d => d.StartsWith(k)).ToList();
However, Jon skeet's answer will probably be more efficient.
Upvotes: 0
Reputation: 1499860
It sounds like you want:
var data = allData.Where(datum => keys.Any(key => datum.StartsWith(key))
.ToList();
Upvotes: 1