Search code examples
c#genericsgeneric-collections

How to add List<Dictionary<string, byte[]> object to Dictionary<string, byte[]>


How to add List<Dictionary<string, byte[]> object to 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 
    }
}

In foreach loop I am getting item.KEYS and item.VALUES so how I can add to it _dickeyValuePairs


Solution

  • If you want to merge them, then something like this:

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

    But beware that if they contain same keys - you will get exception.

    To avoid it - you can use lookup (basically dictionary but in value it stores collection):

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