2010-11-03 200 views
0

我有一个Dictionary<string,string[]> 一些示例值修改字典

Key1 Value="1","2","3","4","5" 
Key2 Value="7","8" 
Key3 Value=null 

我想数组的长度是所有值的最大值这在我的情况下是5键1 这样我就可以得到一个结果作为:

Key1 Value="1","2","3","4","5" 
Key2 Value="7","8","","","" 
Key3 Value="","","","","" 

所以所有的键都有相同的数组长度= 5和前不存在的值是空值“”。 这怎么办?

回答

2

试试这个

 Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>(); 
     dic.Add("k1", new List<string>() { "1", "2", "3", "4", "5" }); 
     dic.Add("k2", new List<string>() { "7", "8" }); 
     dic.Add("k3", new List<string>()); 

     var max = dic.Max(x => x.Value.Count); 
     dic.ToDictionary(
      kvp => kvp.Key, 
      kvp => 
      { 
       if (kvp.Value.Count < max) 
       { 
        var cnt = kvp.Value.Count; 
        for (int i = 0; i < max - cnt; i++) 
         kvp.Value.Add(""); 
       } 
       return kvp.Value; 
      }).ToList(); 
2

我想用类似的方法将Dictionary封装到我自己的类中,除非每次添加值时,如果必须扩展该数组以包含该值,则可以扩展字典中所有其他数组值的大小。

如果要提高效率,每次发生这种情况时都会使数组翻倍,以避免代码效率低下。您可以跟踪所有数组的虚拟“最大大小”,即使您通过将它跟踪在类int变量中来有效地加倍它们。

0
Dictionary<string, string[]> source = GetDictionary(); 

targetSize = source.Values.Select(x => x.Length).Max(); 

Dictionary<string, string[]> result = source.ToDictionary(
    kvp => kvp.Key, 
    kvp => kvp.Value != null ? 
    kvp.Value.Concat(Enumerable.Repeat("", targetSize - kvp.Value.Length)).ToArray() : 
    Enumerable.Repeat("", targetSize).ToArray 
);