【问题标题】:LINQ to change KeyValuePair in dictLINQ 更改 dict 中的 KeyValuePair
【发布时间】:2020-01-28 17:57:38
【问题描述】:

我正在尝试使用正则表达式解析化学式的输入文本。正则表达式应该能够处理多个相同元素,即 CH4 或 CHHHH。

对于我的其他字典,我使用了 if(Dict.ContainsKey(H) Dict[H].Value++;

        int count = 0;

        string chemForm = tbxFormula.Text.ToString();

        string pat = @"(?<Key>[A-Z]|([A-Z][a-z]))(?<Value>[0-9]|() )";


        KVPs = (from Match m in Regex.Matches(chemForm, pat)
                select new
                {
                    key = m.Groups["Key"].Value,
                    value = int.Parse(m.Groups["Value"].Value) ,

                }).ToDictionary(p => p.key, p => p.value);

错误:输入字符串的格式不正确。或“字典中已存在键”。

【问题讨论】:

  • 您需要确保您的密钥中没有重复项。一个键是唯一的,它不能多次存在
  • 您可以在 ToDictionary 之前执行 GroupBy 以对键进行分组并聚合值。

标签: c# regex linq dictionary


【解决方案1】:
try this:

 //string chemForm = "HHO"; // H2 O1
 string chemForm = "CH4N10"; // C1 H4 N10
 var distinctElements = new HashSet<char>();
 var KVPs = new Dictionary<char, int>();

chemForm
.ToUpper()
.ToCharArray()
.Where(c => Regex.Match(c.ToString(), @"[A-Z]").Success)
.ToList()
.ForEach(c => distinctElements.Add(c));

foreach (char c in distinctElements)
{
   Match m = Regex.Match(chemForm,
   $@"(?<element>[{c}]+(?=\D|\b))|(?<quantifiedElement>[{c}][0-9]+)");
    if (!string.IsNullOrEmpty(m.Groups["element"].Value)) KVPs.Add(c, 
   m.Groups["element"].Value.Length);
    if (!string.IsNullOrEmpty(m.Groups["quantifiedElement"].Value)) KVPs.Add(c, 
  int.Parse(m.Groups["quantifiedElement"].Value.Substring(1)));
}

KVPs.Dump();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2019-02-11
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多