Modifying a Dictionary
I have a Dictionary<string,string[]>
Some example values are
Key1 Valu开发者_StackOverflowe="1","2","3","4","5"
Key2 Value="7","8"
Key3 Value=null
I want to the array length to be the max of all values which in my case is 5 for Key1 so I can get a result as:
Key1 Value="1","2","3","4","5"
Key2 Value="7","8","","",""
Key3 Value="","","","",""
So all Keys have same array length = 5 and the values which didnt exist before are empty values "". How can this be done?
Try this
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();
I'd encapsulate a Dictionary into my own class with similar methods, except whenever a value is added, if you must extend that array to contain the value, you extend the size of all other array values in the dictionary.
If you're going for efficiency, I'd double the arrays each time this happens to avoid inefficient code. You can keep track of the virtual 'max size' of all the arrays even if you're effectively doubling them by keeping track of it in a class int variable.
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
);
精彩评论