反对字典,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

标签: c#genericsgeneric-collections

解决方案


如果你想合并它们,那么像这样:

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

推荐阅读