将字典细分为较小的部分

时间:2014-12-04 19:09:40

标签: c# linq dictionary

我试图将字典细分成更小的部分。我的方法有效,我只是想知道是否有更有效的方法。为了这个例子,字典有10个元素,但是我的代码最多可以有1000个,并且我将以50个批量传递给api。

我的Questain有更有效的方法吗?

int divideamount = 2;

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("cat1", "cat");
dictionary.Add("dog2", "cat");
dictionary.Add("cat3", "cat");
dictionary.Add("dog4", "cat");
dictionary.Add("cat5", "cat");
dictionary.Add("dog6", "cat");
dictionary.Add("cat7", "cat");
dictionary.Add("dog8", "cat");
dictionary.Add("cat9", "cat");
dictionary.Add("dog10", "cat");


var divided_dictionary
    = dictionary.Select((value, index) => new { Index = index, Value = value })
                .GroupBy(x => x.Index / divideamount)
                .Select(g => g.Select(x => x.Value).ToDictionary(x => x.Key, x => x.Value))
                .ToList();


foreach (Dictionary<string, string> division in divided_dictionary)
{ 
    // do some work
}

提前感谢您的任何帮助或评论。

1 个答案:

答案 0 :(得分:5)

您可以使用Partition method from moreLINQ library

var divided_dictionary
    = dictionary.Partition(divideamount)
                .Select(x => x.ToDictionary(i => i.Key, i => i.Value));

我刚刚写了一篇关于使用LINQ对集合进行分区的博客文章。您可能会发现它很有用:Partitioning the collection using LINQ: different approaches, different performance, the same result