I wanna use only top N list items and delete the rest. I thought I duplicated & sorted matches as _listTopN but when I clear matches it also clears _listTopN
In short, how can I get the max 3 list items in an unordered dictionary list and put them back that same dictionary?
Dictionary<int, float> matches;
…
if (matches.Count > Settings.requiredMatch)
{
var _listTopN = matches.OrderByDescending(s => s.Value).Take(Settings.requiredMatch);
matches.Clear();
foreach (var p in _listTopN)
matches.Add(p.Key, p.Value);
}
Linq queries are evaluated lazily. Your statement where you assign
_listTopNdoesn’t perform any work, it only prepares the query ; this query will only be executed when you start enumerating the results. Since you clearmatchesbefore you start enumerating the query, there is nothing in the source to enumerate…If you want the query to be evaluated eagerly, add
ToListat the end:Alternatively, you can use
ToDictionaryto perform all the work in a single query: