user1250122
user1250122

Reputation: 51

Refactoring for-loop Linq query into a single query

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

Answers (3)

MatthiasG
MatthiasG

Reputation: 4532

This should do the job:

dataForSingleThreadToProcess = allData.Where(x => keys.Any(x.StartsWith)).ToList();

Upvotes: 0

Rawling
Rawling

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

Jon Skeet
Jon Skeet

Reputation: 1499860

It sounds like you want:

var data = allData.Where(datum => keys.Any(key => datum.StartsWith(key))
                  .ToList();

Upvotes: 1

Related Questions