3

I need to split my dictionary using LINQ expression. I need to split into two parts. Could somebody help me?

var myDictionary = new Dictionary<int, int>();
var halfOfDictionary = myDictionary.ToDictionary(...)
p.s.w.g
  • 141,205
  • 29
  • 278
  • 318
user3818229
  • 1,467
  • 2
  • 19
  • 40
  • 2
    Split it how? You want to get the keys in one collection and the values in another (you don't need Linq for that)? Or you want to construct 2 new dictionaries containing some part of the original pairs based on some condition? Please be more specific. – p.s.w.g Dec 24 '14 at 03:41
  • What is your intent for doing so? There may be better ways of achieving what you're looking for. – Anthony Forloney Dec 24 '14 at 03:42

1 Answers1

4
// remove OrderBy if ordering is not important
var ordered = dictionary.OrderBy(kv => kv.Key);
var half = dictionary.Count/2;
var firstHalf = ordered.Take(half).ToDictionary(kv => kv.Key, kv => kv.Value);
var secondHalf = ordered.Skip(half).ToDictionary(kv => kv.Key, kv => kv.Value);
Tien Dinh
  • 989
  • 6
  • 12