【问题标题】:How to merge n List<Dictionary<string, string>> into a Dictionary using Linq如何使用 Linq 将 n List<Dictionary<string, string>> 合并到字典中
【发布时间】:2019-02-20 16:43:50
【问题描述】:

我尝试使用 linq 将字典列表(动态)合并到一个给定对象的单个列表中,我看到了许多与此类似的问题,但是在他们的情况下,他们总是考虑已知数量的字典。

嗯,这是我的结构:

我有一个返回列表对象的查询,如下所示:

public class MyDto 
{
  public Dictionary<string, string> JsonDictionary { get; set; }
  public Guid SomeId1{ get; set; }
  public Guid SomeId2{ get; set; } 
}

使用 linq 我正在这样做:

var q = _uow.TableWithJson.GetAll()
         .Include(a=> a.TableId1)
         .Include(a=> a.TableAux)
             .ThenInclude(b=> b.TableId2)
         .Select(r => new MyDto
             {
                SomeId1 = r.tableId1.Id,
                SomeId2 = r.tableId2.Id,
                JsonDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(r.JsonContent)
             });

最后,我得到了这样的结果;

{
  SomeId1: xxxxx,
  SomeId2: yyyyy,
  JsonDictionary: [
    {key: key1, value: value 1}
    {key: key1, value: value 2}
    {key: key1, value: value 3}
    {key: key1, value: value 4}
  ],
},
{
  SomeId1: xxxxx,
  SomeId2: yyyyy,
  JsonDictionary: [
    {key: key4, value: value 4}
    {key: key5, value: value 5}
    {key: key6, value: value 6}
  ],
}, // many other objects with different ids and different dictionaries.

如你所见,在上面的 sn -p 中 SomeId1 和 SomeId2 两个对象是相同的。因此,在这种情况下,我想将这些对象分组,将 JsonContent 字段合并到一个字典中。

也尝试使用 .GroupBy 但我无法将此 jsonContent 合并为一个聚合。

帮助!!!请! =) 拥抱

【问题讨论】:

  • 你试过 Enumerable.Zip docs.microsoft.com/en-us/dotnet/api/…
  • 您可以通过覆盖 HashSet 并将您的 someid 定义为指定重复的键来执行此类操作,但仅当键和内容相同时才返回 false 否则只需添加内容.. .
  • 除非 ID1 和 ID2 相同,否则不能合并。如果它们相同,则必须检查键是否已存在,因为您不必在字典中键入相同的键。

标签: c# entity-framework linq .net-core


【解决方案1】:

如果您想以这种方式执行此操作,则可以使用...但是,您没有提供如何处理与具有相同键但不同值的 JsonDictionaries 的冲突。在这种情况下,我只是覆盖了之前声明的值。如果你想要不同的行为,你必须改变它。

IEnumerable<MyDto> list = new List<MyDto>(); // This is the stuff you parsed
var results = new Dictionary<Tuple<Guid, Guid>, MyDto>();

foreach (var item in list) {
    var key = new Tuple<Guid, Guid>(item.SomeId1, item.SomeId2);
    if (results.ContainsKey(key))
        foreach (var entry in item.JsonDictionary)
            results[key].JsonDictionary[entry.Key] = entry.Value;
    else results[key] = item;
}

list = results.Values;

更新:

如果你真的想要的话,我用 Linq 写的。这是非常低效的,但我想不出很多其他方法来轻松做到这一点。如果你想要效率,你应该使用上面的例子。

var results = list
    .GroupBy(
        x => new Tuple<Guid, Guid>(x.SomeId1, x.SomeId2), 
        (x, y) => new MyDto {
                SomeId1 = x.Item1,
                SomeId2 = x.Item2,
                JsonDictionary = y
                    .SelectMany(z => z.JsonDictionary)
                    .ToLookup(z => z.Key, z => z.Value)
                    .ToDictionary(z => z.Key, z => z.First())
        });

【讨论】:

  • 太棒了@Aotn!谢谢!!
【解决方案2】:

这么快的想法,不确定这是否可以完全在 linq 本地完成。

// lets group all of our id's and I'm not going to use groupby because I'm not a fan.
var itemsById = new Dictionary<string, List<MyDto>>();
foreach(var item in q)
{
   if(itemsById.ContainsKey(item.SomeId))
   {
       itemsById[item.SomeId].Add(item);
   }
   else 
   {
      itemsById.Add(item.SomeId, new List<MyDto>());
      itemsById[item.SomeId].Add(item);
   } 
}

so now we have dictionary of all of items by their ID.

var finalizedDtos = new List<MyDto>();
foreach(var entry in items)
{
   var finalizedDto = new MyDto{ someId = entry.Key };
   foreach(var innerDictionary in entry.value.JsonDictionary)
   {
                    var finalizedDto = new MyDto {SomeId = entry.Key};
                    var allKeyValuePairs = entry.Value.SelectMany(c => c.JsonDictionary);
                    finalizedDto.JsonDictionary = allKeyValuePairs.ToDictionary(key => key.Key, value => value.Value);
                    finalizedDtos.Add(finalizedDto);
   }
}

不是很多 linq,但对于嵌套结构,我真的想不出更好的计划

【讨论】:

  • 谢谢 Jlalonde,我遇到了与这段代码的一些冲突……但无论如何,谢谢!!
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多