1

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
jelo
  • 13
  • 2

2 Answers2

3
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.

AD.Net
  • 13,352
  • 2
  • 28
  • 47
  • Thank you so much! I was thinking and changing codebut finally has been a simple change! :) – jelo Nov 04 '15 at 11:53
0

An alternative to using Except is to add a where clause in the LINQ expression:

var items = (from pair in dic
             orderby pair.Value descending
             where !res.ContainsKey(pair.Key.ToString())
             select pair);
var top5 = items.Take(5).ToArray();
Serguei
  • 2,910
  • 3
  • 24
  • 34