根据值标准构造新的Dictionary

时间:2015-05-06 15:13:30

标签: c# .net vb.net linq

我想从

构建一个字典
Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
dict.Add(1, new List<string>() { "1", "2", "3" });
dict.Add(2, new List<string>() { "4", "5", "6" });
dict.Add(3, new List<string>() { "7", "8", "9" });

这样的条件是List的值的计数满足给定的整数 i

例: i=4 我希望结果是

Dictionary<int, List<string>> res= new Dictionary<int, List<string>>();
dict.Add(1, new List<string>() { "1", "2", "3" });
dict.Add(2, new List<string>() { "4"});

i=7 我希望结果是

Dictionary<int, List<string>> res= new Dictionary<int, List<string>>();
dict.Add(1, new List<string>() { "1", "2", "3" });
dict.Add(2, new List<string>() { "4", "5", "6" });
dict.Add(3, new List<string>() { "7"});

我尝试使用Take while for i = 5但是它不值得。

var res = dict.Select(x => x).TakeWhile(y => dict.Values.ToList().Count < 6);

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以遍历原始字典并计算每次迭代的值计数,然后填充结果字典,如:

//Arrange
var original = new List<int>{1001,1002,1003,1004,1005,1006,1007,1008,1009,1010};

//Act 
var shuffled = Shared_Components.SharedComponents.Shuffle(original , 10);

//Assert
shuffled.Should().BeEquivalentTo(original)
    .And.NotBeAscendingInOrder();

DEMO