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
  • 146,324
  • 30
  • 291
  • 331
user3818229
  • 1,537
  • 2
  • 21
  • 46
  • 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
  • 1,037
  • 7
  • 12
  • This assumes (dictionary.Count % 2 == 0). Unless C# is different with integer division – Braden Brown Aug 31 '18 at 14:41
  • @BradenBrown I don't see a problem with the division. The div result is an int. The same number is taken and skipped (no off-by-one mistake). – mafu Sep 13 '19 at 13:05