开发者

idictionary help filtering items

Is there a better way to code the Where this:

    IDictionary<string, string> p = new Dictionary<string, string>();
    p.Add("Apple", "1");
    p.Add("Orange", "2");
    p.Add("Pear", "3");
    p.Add("Grape", "4");
    p.Add("Pineapple", "5");
    //This开发者_StackOverflow社区 is a unique list

    var retVal = p.Where(k => k.Key.Contains("Apple") || k.Key.Contains("Pear") || k.Key.Contains("Grape"));

Some History Below

I have a dictionary of strings like the following:

IDictionary<string,string>

The contents look like this:

Apple,1
Orange,2
Pear,3
Grape,4
...many more

How do i return only a few items from my dictionary like so

if (true)
{
  //return only 3 apple,pear&grape items out of the dozens in the list into a new variable
}


You can just take the first 3 items...

theDictionary.Take(3);

Or filter and take specific items...

string[] itemsIWant = { "Apple", "Pear", "Grape" };

theDictionary.Where(o => itemsIWant.Contains(o.Key));

Or sort randomly and take 3...

Random r = new Random();

theDictionary.OrderBy(o => r.Next()).Take(3);


check out LINQ query to return a Dictionary<string, string>


That will really depend on the kind of filtering you want to achieve. But you can achieve it through Linq.

If you just want to get the first 3 items, you can do it like this:

theDictionary.Take(3);

If you want to get the first 3 items that begin with 'G', the you will do this:

theDictionary.Where(kv => kv.Key.StartsWith("G")).Take(3);

If you want to get the first 3 items that begin with 'G' regardless the casing, the you will do this:

theDictionary.Where(kv => kv.Key.ToLower().StartsWith("g")).Take(3);

Last, but not least, if you want to get 3 items randomly, you will do this:

Random rand = new Random();
theDictionary.OrderBy(kv => rand.Next()).Take(3);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜