【问题标题】:c# combine dictionary values into new key value pairc# 将字典值组合成新的键值对
【发布时间】:2021-11-04 03:34:29
【问题描述】:

我有一个这样的 c# 字典:

我需要做的是将字典键包含“UPC”的值组合成一个具有组合值的新键,因此它如下所示: {[UPC, 000000000333, 789787878999]}

UPC 可以包含一个或多个值。

我想出了下面的代码,首先从信息字典中删除可能的重复项

//Remove any duplicates
        List<string> vals = new List<string>();
        Dictionary<string, string> newDict = new Dictionary<string, string>();
        foreach (KeyValuePair<string, string> item in information)
        {
            if (!vals.Contains(item.Value))
            {
                newDict.Add(item.Key, item.Value);
                vals.Add(item.Value);
            }
        }

        StringBuilder sbUPC = new StringBuilder();
        
        var newDictJustUPCs = newDict.Where(kvp => kvp.Key.Contains("UPC"));

newDictJustUPCs 返回以下内容:

那么我将如何遍历这些 KeyValuePairs 并为具有键“UPC”的 newDict 和组合的两个值创建 KeyValue 对并将其分配给 newDict?

我知道最终答案的一部分将是 newDict.Add("UPC", CombinedUPCValues);

【问题讨论】:

    标签: c# dictionary key-value


    【解决方案1】:

    您可以通过多种方式做到这一点。这里只有一个

    给定

    var dict = new Dictionary<string, string>
    {
       { "asd", "dfgdfg" },
       { "ghj", "ghj" },
       { "UPC1", "123" },
       { "UPC2", "345" },
       { "UPC3", "567" }
    };
    

    用法

    var upc = dict
       .Where(x => x.Key.StartsWith("UPC"))
       .Select(x => x.Value);
    
    var newDict = dict
       .Where(x => !x.Key.StartsWith("UPC"))
       .ToDictionary(x => x.Key, x => x.Value);
    
    newDict.Add("UPC", string.Join(",", upc));
    
    
    foreach (var item in newDict)
        Console.WriteLine(item.Key + " : "+ item.Value);
    

    输出

    asd : dfgdfg
    ghj : ghj
    UPC : 123,345,567
    

    【讨论】:

      【解决方案2】:

      首先提取所有 UPC 元素并根据需要创建其值,然后将其附加到没有 UPC 元素的新数组中

                  var dict = new Dictionary<string, string>
              {
                  {"Modified by", "Stuart gill" },
                  {"Modified on", "11/2/2021" },
                  {"UPC0", "000000000333" },
                  {"UPC2", "789789789" },
              };
      
             var keyValueWithUpc = dict.Where(kv => kv.Key.StartsWith("UPC")).ToArray();
             var upcValue = string.Join(",", keyValueWithUpc.Select(kv => kv.Value));
             var result = dict.Except(keyValueWithUpc)
                               .Append(new KeyValuePair<string, string>("UPC", upcValue))
                               .ToDictionary(x => x.Key, x => x.Value);
      

      Append 方法:它需要源(附加的集合)一个数组而不是一个数组,只是为了与现有的一个进行区分,但是由于它作为一个参数,你也可以传递单个项目

      public static class ExtensionMethods
      {
          public static IEnumerable<T> Append<T>(this IEnumerable<T> source, params T[] itemsToAppend)
          {
              return source.Concat(itemsToAppend);
          }
      }
      

      【讨论】:

      • 我尝试了您的建议,并在 .Append 上指出 IEnumerable> 'type' 的编译器错误 CS1061 不包含 'name' 的定义并且没有可访问的扩展名可以找到接受“type”类型的第一个参数的方法“name”(您是否缺少 using 指令或程序集引用?)。当您尝试调用方法或访问不存在的类成员时会发生此错误。
      • 它在 Enumerable 类中可用,适用于 .Net5.0 。您可以创建自己的喜欢编辑的答案
      【解决方案3】:

      TheGeneral 用他的代码示例为我指明了正确的方向。这是我的解决方案。传入以下日志信息。

      StringBuilder sb = new StringBuilder();
              Dictionary<string, string> information = new Dictionary<string, string>();
              List<string> changes = log.Changes.ToString().Split('?').ToList();
              changes.RemoveAt(changes.Count - 1);
              
              int start = 0;
              
              foreach (string units in changes)
              {
                  string[] unit = units.Split('|');
                  string[] parts = unit[0].Split('-');
                  string[] values = unit[1].Split('^');
      
                  string field = parts[1];
                  string orig = values[0];
                  
                  if (unit[0] == "VendorPartUpc-UPC")
                  {
                      information.Add(field+start, values[1]);
                      start = start + 1;
                  }
                  else if (values.Count() > 1 && (orig != string.Empty || values[1] != string.Empty) && !information.ContainsKey(field))
                      information.Add(field, values[1]);
              }
      
              //Remove any duplicates
              List<string> vals = new List<string>();
              Dictionary<string, string> newDict = new Dictionary<string, string>();
              foreach (KeyValuePair<string, string> item in information)
              {
                  if (!vals.Contains(item.Value))
                  {
                      newDict.Add(item.Key, item.Value);
                      vals.Add(item.Value);
                  }
              }
              
              //Need to take the UPCs from multiple key/value pairs, extract just the UPC value and put into a single value with UPC as the key.
              var newDictJustUPCs = newDict.Where(kvp => kvp.Key.Contains("UPC"));
              var upc = newDictJustUPCs
                  .Where(x => x.Key.StartsWith("UPC"))
                  .Select(x => x.Value);
      
              newDict.Add("UPC", string.Join(",", upc));
               
              information = newDict;
      
              return information;
      

      【讨论】:

        猜你喜欢
        • 2016-08-23
        • 2018-09-18
        • 2011-04-28
        • 1970-01-01
        • 1970-01-01
        • 2018-04-16
        • 1970-01-01
        • 2019-04-06
        • 1970-01-01
        相关资源
        最近更新 更多