如何将字典拆分为“n”部分

时间:2014-12-24 03:39:40

标签: c# linq

我需要使用LINQ表达式拆分字典。我需要分成两部分。有人能帮助我吗?

var myDictionary = new Dictionary<int, int>();
var halfOfDictionary = myDictionary.ToDictionary(...)

1 个答案:

答案 0 :(得分:3)

// 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);