How to add List<Dictionary<string, byte[]> object to Dictionary<string, byte[]>
本问题已经有最佳答案,请猛点这里访问。
如何将
1 2 3 4 5 6 7 8 9 10 | public static async void PostUploadtoCloud( List<Dictionary<string, byte[]>> _commonFileCollection) { Dictionary<string, Byte[]> _dickeyValuePairs = new Dictionary<string, byte[]>(); foreach (var item in _commonFileCollection) { _dickeyValuePairs.add(item.key,item.value); // i want this but I am getting //_dickeyValuePairs.Add(item.Keys, item.Values); so I am not able to add it dictionary local variable _dickeyValuePairs } } |
在foreach循环中,我得到了
在执行此操作时,需要在代码中使用一些安全性,像@pritish所说的简单合并由于可能的异常而无法工作,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public static async void PostUploadtoCloud(List<Dictionary<string, byte[]>> _commonFileCollection) { Dictionary<string, Byte[]> _dickeyValuePairs = new Dictionary<string, byte[]>(); try { foreach (var item in _commonFileCollection) { foreach (var kvp in item) { //you can also use TryAdd if(!_dickeyValuePairs.Contains(kvp.Key)) { _dickeyValuePairs.Add(kvp.Key, kvp.Value); } else { //send message that it could not be done? } } } } catch(Exception e) { //log exception } } |
。
尝试如下修改循环:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static async void PostUploadtoCloud(List<Dictionary<string, byte[]>> _commonFileCollection) { Dictionary<string, Byte[]> _dickeyValuePairs = new Dictionary<string, byte[]>(); Byte[] itemData; foreach (var item in _commonFileCollection) { foreach (var kvp in item) { if (!_dickeyValuePairs.TryGetValue(kvp.Key, out itemData)) { _dickeyValuePairs.Add(kvp.Key, kvp.Value); } } } } |
更新:
外部循环将遍历列表中的每个字典,其中,内部循环将迭代字典的每个项。附加部分
如果要合并它们,则如下所示:
1 2 3 4 | public static async void PostUploadtoCloud( List<Dictionary<string, byte[]>> _commonFileCollection) { var _dickeyValuePairs = _commonFileCollection.SelectMany(x=> x).ToDictionary(x=> x.Key, x=> x.Value); } |
但要注意,如果它们包含相同的键,您将得到异常。
为了避免它-您可以使用查找(基本上是字典,但在值中它存储集合):
1 2 3 4 | public static async void PostUploadtoCloud( List<Dictionary<string, byte[]>> _commonFileCollection) { var _dickeyValuePairs = _commonFileCollection.SelectMany(x=> x).ToLookup(x=> x.Key, x=> x.Value); //ILookup<string, IEnumerable<byte[]>> } |
号