【问题标题】:How to get nested key value pair from dictionary with linq [duplicate]如何使用linq从字典中获取嵌套键值对[重复]
【发布时间】:2020-02-08 17:57:54
【问题描述】:

我有一个 lstSubs List<KeyValuePair<string, string> 其中包含值

  • FNAME,“ABC”
  • LNAME "XYZ"
  • VAR001,“VAR002”
  • VAR002,“VAR001 的实际值”
  • VAR003,“VAR004”
  • VAR004 , "VAR005"
  • VAR005,“VAR003 的实际值”

我有一个字符串,例如 envelop "Hello [FNAME] [LNAME],您创建了一个对 [VAR001] 的请求,该请求已分配给 [VAR003]"

 var regex = new Regex(@"\[(.*?)\]");
                    var matches = regex.Matches(envelop.ToString());
                    foreach (Match match in matches) 
                    {  
                       columnValue = linq to get the value from the list based on key;
                       envelop.Replace(match.Value, columnValue);
                    }

在此,直接的 Key,Value 对很容易通过 Linq 获得,但我很难获取嵌套在连接 Key,Value 方面的复杂值。


在 LINQ 中是否有任何方法或必须使用循环。 预期输出:您好 ABC XYZ,您创建了一个对 ActualValueforVAR001 的请求,该请求已分配给 ActualValueforVAR003

谢谢, PS。代码不完整。它是整个代码的一部分,旨在使其简洁发布

已编辑:由于格式设置,我的某些文本不可见。 当我根据配置它们的某些条件创建它们时,它们的字典值是嵌套的

【问题讨论】:

  • 你没有字典。
  • VAR001 指向 VAR002,所以你认为当字符串被替换时,VAR001 应该替换为 VAR002 的实际值,VAR003 应该替换为 VAR005 的实际值?

标签: c# regex linq


【解决方案1】:

首先,让我们把初始的List<T> 变成Dictionary<K, V>

  List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>() {
    new KeyValuePair<string, string>("FNAME", "ABC"),
    new KeyValuePair<string, string>("LNAME", "XYZ"),
    new KeyValuePair<string, string>("VAR001", "VAR002"),
    new KeyValuePair<string, string>("VAR002", "ActualValueforVAR001"),
    new KeyValuePair<string, string>("VAR003", "VAR004"),
    new KeyValuePair<string, string>("VAR004", "VAR005"),
    new KeyValuePair<string, string>("VAR005", "ActualValueforVAR003"),
  };

  Dictionary<string, string> dict = list.ToDictionary(
    pair => pair.Key, 
    pair => pair.Value,
    StringComparer.OrdinalIgnoreCase); // Comment out if should be case sensitive

  // Some values can be nested
  while (true) {
    bool nestedFound = false;

    foreach (var pair in dict.ToList()) {
      if (dict.TryGetValue(pair.Value, out var newValue)) {
        dict[pair.Key] = newValue;
        nestedFound = true;
      }
    }

    if (!nestedFound)
      break;
  }

那么对于给定的envelop

  string envelop = 
    @"Hello [FNAME] [LNAME] you have created a request for [VAR001] which got assigned to [VAR003]";

你可以把一个简单的Regex.Replace:

  string result = Regex
    .Replace(envelop,
           @"\[[A-Za-z0-9]+\]",
             m => dict.TryGetValue(m.Value.Trim('[', ']'), out var value) ? value : "???");

  Console.Write(result);

结果:

  Hello ABC XYZ you have created a request for ActualValueforVAR001 which got assigned to ActualValueforVAR003

【讨论】:

  • 抱歉给您添麻烦了。但我认为我无法清楚地提出这一点。我需要通过keys遍历找到ActualValue。谢谢
  • @Amit Singh:我明白了;你有 嵌套 值;初始字典创建后需要一些循环;我已经编辑了答案
  • 太棒了,我实际上做了同样的事情,但你的代码很干净。会用这个。感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 2014-06-21
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
相关资源
最近更新 更多