如何将List <dictionary <string,byte [] =“”>对象添加到Dictionary <string,byte [] =“”>

时间:2018-08-23 06:46:18

标签: c# generics generic-collections

如何将List<Dictionary<string, byte[]>对象添加到Dictionary<string, byte[]>

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循环中,我得到item.KEYSitem.VALUES,因此我可以添加它 _dickeyValuePairs

3 个答案:

答案 0 :(得分:1)

如果要合并它们,则如下所示:

public static async void PostUploadtoCloud( List<Dictionary<string, byte[]>> _commonFileCollection)
{
    var _dickeyValuePairs = _commonFileCollection.SelectMany(x=> x).ToDictionary(x=> x.Key, x=> x.Value);
}

但是请注意,如果它们包含相同的密钥-您将获得异常。

为避免这种情况-您可以使用查找(基本上是字典,但其值存储集合):

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[]>>
}

答案 1 :(得分:1)

尝试如下所示的修改循环:

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);
            }
        }

    }
}

更新

外部循环将遍历列表中的每个字典,而内部循环将遍历字典中的每个项目。附加部分_dickeyValuePairs.TryGetValue将帮助您避免在添加重复键(如果有)时出现异常。

答案 2 :(得分:1)

执行此操作时,您需要在代码中使用一些安全性,像@Pritish这样的简单合并会由于可能的异常而无法正常工作,

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
 } 
}