score:5

Accepted answer

linq queries are evaluated lazily. your statement where you assign _listtopn doesn't perform any work, it only prepares the query ; this query will only be executed when you start enumerating the results. since you clear matches before you start enumerating the query, there is nothing in the source to enumerate...

if you want the query to be evaluated eagerly, add tolist at the end:

var _listtopn = matches.orderbydescending(s => s.value)
                       .take(settings.requiredmatch)
                       .tolist();

alternatively, you can use todictionary to perform all the work in a single query:

matches = matches.orderby(s => s.value)
                 .take(settings.requiredmatch)
                 .todictionary(s => s.key, s => s.value);

score:1

if (matches.count > settings.requiredmatch)
  matches = matches.orderbydescending(s => s.value)
  .take(settings.requiredmatch)
  .todictionary(s => s.key, s => s.value);

gets matches into the state you want simply and clearly.

score:2

that is because _listtopn is holding on to a deferred query, lazily executed when you loop on it.

in other words, var _listtopn = ... does not evaluate the query, it returns a recipe for how to evaluate it when needed.

since you clear the underlying source before you evaluate it, it'll "change", that is, return something other than what you wanted/expected.

the simple fix is to force evaluation, so do this:

var _listtopn = matches.orderbydescending(s => s.value)
    .take(settings.requiredmatch).toarray();
                                 ^--------^  <-- add this

this evaluates your query and stores the result as an array that won't change, and now you can safely clear your underlying data source.

score:2

your linq expression _listtopn is lazily evaluated which means that it doesn't evaluate its result until your foreach statement. but at this point you have already cleared matches source, so you get nothing in _listtopn also. you can force linq methods to evaluate their results by calling toarray for example.

 var _listtopn = matches.orderbydescending(s => s.value).take(settings.requiredmatch)
                          .toarray(); 

see this statement in msdn

this method is implemented by using deferred execution

score:3

force it to evaluate earlier:

var _listtopn = matches.orderbydescending(s => s.value)
    .take(settings.requiredmatch).tolist();

linq has deferred execution (as part of composition); in most cases, nothing is actually evaluated until you foreach over the data. the tolist() makes this happen earlier, i.e. before you clear the dictionary.

score:3

you can assign the result to matches with todictionary:

if (matches.count > settings.requiredmatch)
{
    matches = matches
        .orderbydescending(s => s.value)
        .take(settings.requiredmatch)
        .todictionary(kvp => kvp.key, kvp => kvp.value);
}

Related Query