简体   繁体   English

将字典细分成较小的部分

[英]Sub divide a dictionary into smaller parts

I am trying to sub divide a dictionary into smaller parts. 我试图将字典细分成较小的部分。 My approach works, I am just wondering if there is a more efficient way of doing it. 我的方法行得通,我只是想知道是否有更有效的方法。 For the sake of the example, the dictionary has 10 elements but my code can have up to 1000 and would be in batches of 50 to which I am passing to an api. 就本例而言,字典有10个元素,但是我的代码最多可以包含1000个元素,并且将以50个为批次,我将这些代码传递给api。

My Questain is there a more efficient way of doing this...? 我的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
}

Thanks in advance for any help or comments. 在此先感谢您的帮助或评论。

You can use Partition method from moreLINQ library . 您可以使用moreLINQ库中的Partition方法

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

I wrote a blog post about partitioning collections using LINQ a while ago. 不久前,我写了一篇有关使用LINQ对集合进行分区的博客文章。 You may find it useful: Partitioning the collection using LINQ: different approaches, different performance, the same result . 您可能会发现它很有用: 使用LINQ对集合进行分区:不同的方法,不同的性能,相同的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM