Search code examples
linqunions

Dynamic LINQ Unions possible?


Is it possible to dynamically add UNION clauses in LINQ? I have a list of RssFeed collections that I want to aggregate but the number of feeds is not known ahead of time. But I would like to be able to union them all and take the most recent 10 posts from the bunch.

I guess I could just do a foreach iteration of each feed query and manually add the results to a "master" collection which I could then query by date, but is that the best way?

Ideally I would like to do something like

foreach(RssFeed in myFeeds)
{
  // compose a linq query for the current feed and union it with 
  // the results of the last iteration
}

Solution

  • Like this:

    var query = Enumerable.Empty<Something>();
    
    foreach(RssFeed in myFeeds) {
        query = query.Union(something);
    }