Situation: I have a List<IQueryable<MyDataStructure>> . I want to run one linq query on each of them in parallel and then join the results.
Question: How to create a linq query that I can pass as a parameter?
Code example:
Here is some simplified code. Firstly, I have a collection of IQueryable<string> :
public List<IQueryable<string>> GetQueries() { var set1 = (new List<string> { "hello", "hey" }).AsQueryable(); var set2 = (new List<string> { "cat", "dog", "house" }).AsQueryable(); var set3 = (new List<string> { "cat", "dog", "house" }).AsQueryable(); var set4 = (new List<string> { "hello", "hey" }).AsQueryable(); var sets = new List<IQueryable<string>> { set1, set2, set3, set4 }; return sets; }
I would like to find all the words that start with the letter "h". With one IQueryable<string> this is easy:
query.Where(x => x.StartsWith("h")).ToList()
But I want to run the same query with all IQueryable<string> objects in parallel, and then combine the results. Here is one way to do this:
var result = new ConcurrentBag<string>(); Parallel.ForEach(queries, query => { var partOfResult = query.Where(x => x.StartsWith("h")).ToList(); foreach (var word in partOfResult) { result.Add(word); } }); Console.WriteLine(result.Count);
But I want this to be a more general solution. So that I can separately define the linq operation and pass it as a parameter to the method. Something like that:
var query = Where(x => x.FirstName.StartsWith("d") && x.IsRemoved == false) .Select(x => x.FirstName) .OrderBy(x => x.FirstName); var queries = GetQueries(); var result = Run(queries, query);
But I am at a loss on how to do this. Any ideas?