Accepted answer

a linq query is really nothing other than a method call. as such, you can't "reassign" the object to which you've already called a method after it's been setup.

you could simulate this by creating a wrapper class that would allow you to change what actually gets enumerated, ie:

public class mutatingsource<t> : ienumerable<t>
     public mutatingsource(ienumerable<t> originalsource)
         this.source = originalsource;

     public ienumerable<t> source { get; set; }

     ienumerator ienumerable.getenumerator()
         return this.getenumerator();

     public ienumerator<t> getenumerator()
        return source.getenumerator();

this would allow you to create the query, then "change your mind" after the fact, ie:

var somestrings = new list<string> { "one", "two", "three" };

var source = new mutatingsource<string>(somestrings);

// build the query
var query = source.where(i => i.length < 4);

source.source = new[] {"foo", "bar", "baz", "uh oh"};

foreach(var item in query)

this will print foo, bar, and baz (from the "changed" source items).

edit in response to comments/edit:

i guess one parallel that i'm (maybe erroneously) making is with regular expression: one can compile a regular expression and then apply it to any string. i'd like to do the same with queries and dictionaries.

a query is not like a regular expression, in this case. the query is translated directly into a series of method calls, which will only work against the underlying source. as such, you can't change that source (there isn't a "query object", just the return value of a method call).

a better approach would be to move the query into a method, ie:

ienumerable<tkey> querydictionary<tkey,tvalue>(idictionary<tkey,tvalue> dictionary)
    var keys =  from entry in dictionary
        where entry.value < 5
        select entry.key;
    return keys;

you could then use this as needed:

var query1 = querydictionary(d1);
var query2 = querydictionary(d2);

Related Query

More Query from same tag