Search code examples
c#dictionaryexcepttake

Take n element except from dictionary


I have this code:

var items = from pair in dic orderby pair.Value descending select pair;
var top5 = items.Take(5);

I take five items from a Dictionary string,int in descending order

var keys = String.Join(", ", top5.Select(x => String.Format("{0}", x.Key)).ToArray().Except(res.Keys));

Here I show the 5 items but I except some words placed in another Dictionary string, string. If I except one word in the top5 I will display less than 5 elements.

How can I display always 5 elements although I except some words?


Solution

  • var items = from pair in dic orderby pair.Value descending select pair;
    var keys = items.Select(x => String.Format("{0}", x.Key)).ToArray().Except(res.Keys);
    var top5 = keys.Take(5);
    var result = String.Join(", ", top5);
    

    Do the .Take after you've done the exclusion. And then do the formatting. You can combine some of these into one linq statement.