【问题标题】:How to add items to a dictionary from a linq query?如何从 linq 查询中将项目添加到字典中?
【发布时间】:2017-11-12 06:18:43
【问题描述】:

我正在尝试检查具有属性“id”的节点disp-formula 的xml 文件,并且该属性包含像deqnX-Y 这样的值,其中X 和Y 都是整数,如果找到匹配项,则按以下方式将它们添加到字典中

Key                             Value
"rid="deqnX""               "rid="deqnX-Y""
"rid="deqnX+1""             "rid="deqnX-Y""
...  ...
"rid="deqnY""               "rid="deqnX-Y""

incrementing value of X by 1 till it reaches Y

我已经尝试了下面的代码,但是中途卡住了,我不知道该怎么做。

 Dictionary<string, string> dict = new Dictionary<string, string>();

            XDocument doc = XDocument.Load(@"D:\Practice\test.xml",LoadOptions.PreserveWhitespace);
            var x =from y in doc.Descendants("disp-formula")
                   where y.Attribute("id").Value.Contains(@"deqn(\d+)-(\d+)")
                   select y.Attribute("id");
            foreach (var item in x)
            {

                dict.Add(item);
            }

这是一个示例 xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<article article-type="research">
<front>
<journal-meta>
<issn pub-type="paper">0327-286X</issn>
<publisher>
<publisher-name>IEEE</publisher-name>
</publisher>
</journal-meta>
<article-meta>
<article-id pub-id-type="doi">10.1245/11.202136</article-id>
<title-group>
<article-title>Dragon Ball Super popularity in USA</article-title>
</title-group>
</article-meta>
</front>
<body>
<sec id="S1">
<label>1.</label>
<p>....
<disp-formula id="deqn1">
...
</disp-formula>
</p>
</sec>
<sec id="S2">
<label>2.</label>
<p>...
<disp-formula id="deqn2-6">
...
</disp-formula></p>
<p>...
<disp-formula id="deqn7">
...
</disp-formula>
</p>
<p><disp-formula id="deqn8-10">
...
</disp-formula></p>
</sec>
</body>
</article>

这应该是程序运行后的字典项

Key                             Value
"rid="deqn2""               "rid=""deqn2-6""
"rid="deqn3""               "rid=""deqn2-6""
"rid="deqn4""               "rid=""deqn2-6""
"rid="deqn5""               "rid=""deqn2-6""
"rid="deqn6""               "rid=""deqn2-6""
"rid="deqn8""               "rid=""deqn8-10""
"rid="deqn9""               "rid=""deqn8-10""
"rid="deqn10""              "rid=""deqn8-10""

【问题讨论】:

  • 您不能将item 添加到dic,因为它不是Add 的对应参数
  • 您需要解释更多有关问题域的信息。我不明白算法应该是什么。无论如何,您可以使用这样的东西来转换为字典,但正如我所说,您需要解释更多应该输出的内容。 var dict = x.ToDictionary(o =&gt; new {o.Name, o.Value});
  • string.Contains 方法接受正则表达式,但是是简单的字符串。
  • 你能显示完整的 disp-formula 条目吗?或者解释一下 Y 值在哪里?
  • @pmcilreavy 我想找到节点 disp-formula 的 xml 文件,其 id 具有结构 deqnX-Y,然后只需将该值 deqnX-Y 作为 字典中的值 和相应的 keys 应该是 deqnX 到 deqnY 其中 X = X+1,

标签: c# linq dictionary


【解决方案1】:

这个问题包括:

  1. 查找与正则表达式匹配的元素
  2. 从匹配的字符串中获取 X 和 Y
  3. 增加 X 直到 Y 并将它们存储在字典中

var dict = new Dictionary<string, string>();
var xdoc = XDocument.Load(@"D:\Practice\test.xml", LoadOptions.PreserveWhitespace);
var regex = new Regex(@"deqn(\d+)-(\d+)");

// Get matches by the regex
var matches = from dispFormula in xdoc.Descendants("disp-formula")
                select regex.Match(dispFormula.Attribute("id").Value);
// We want only successes
matches = matches.Where(match => match.Success);

foreach (var match in matches)
{
    // If input string is "deqn2-6", 
    //   match.Groups[0].Value = "deqn2-6", 
    //   match.Groups[1].Value = "2", 
    //   match.Groups[2].Value = "6", so
    int x = int.Parse(match.Groups[1].Value);
    int y = int.Parse(match.Groups[2].Value);

    // Now we have to increment x until y
    for (int i = 0; x + i <= y; i++)
    {
        dict.Add($"deqn{x + i}", $"deqn{x}-{y}");
    }
}

foreach (var entry in dict)
{
    Console.WriteLine($"Key={entry.Key}, Value={entry.Value}");
}

这个输出

Key=deqn2, Value=deqn2-6
Key=deqn3, Value=deqn2-6
Key=deqn4, Value=deqn2-6
Key=deqn5, Value=deqn2-6
Key=deqn6, Value=deqn2-6
Key=deqn8, Value=deqn8-10
Key=deqn9, Value=deqn8-10
Key=deqn10, Value=deqn8-10

【讨论】:

  • 非常感谢迈克..:)
  • @Bumba 很高兴,很高兴能为您提供帮助 :)
  • 顺便说一句,如果我一个一个地对一组 xml 文件执行此操作,我是否应该将 dict.Clear() 命令放在最后一个 foreach 循环之后,因为每个文件的字典项都会不同,并且有些文件甚至可能没有节点 disp-formula 或者可能没有带有数字范围的 id 属性。
  • @Bumba 这真的取决于用例。如果您想要每个 xml 文件的字典,我认为您应该将代码放在一个新方法中,该方法接受一个 xml 文件并返回一个字典,然后在每个 xml 文件上调用它。
【解决方案2】:
Dictionary<string, string> dict = new Dictionary<string, string>();

var regex = new Regex(@"deqn(\d+)-(\d+)");

XDocument doc = XDocument.Load(@"D:\Practice\test.xml", LoadOptions.PreserveWhitespace);
var x = from y in doc.Descendants("disp-formula")
        let m = regex.Match(y.Attribute("id").Value)
        where m.Success
        select m;


foreach (var item in x)
{
    var from = int.Parse(item.Groups[1].Value);
    var to = int.Parse(item.Groups[2].Value);
    for (int i = from; i <= to; i++)\\< should be <=
        dict.Add("deqn" + i, item.Value);
}

【讨论】:

  • 您的代码在字典中缺少 Y 部分。即 deqn6 和 deqn10 在输出中丢失。
【解决方案3】:

我已经测试了您的代码,但它不适用于您提供的 Xml

所以最好使用Regex 来查找你的序列,如下代码:

 Dictionary<string, string> dict = new Dictionary<string, string>();
 XDocument doc = XDocument.Load(@"C:\Practice\test.xml", LoadOptions.PreserveWhitespace);
 Regex reg = new Regex(@"deqn(\d+)-(\d+)");
 var x = from y in doc.Descendants("disp-formula").ToList()
                where reg.IsMatch(y.Attribute("id").Value)
                select y.Attribute("id");

正如我在评论中告诉你的,你不能将item 添加到dic,对于计数器,你也可以使用Regex 获取第一个数字,然后将其增加为:

int counter = 0;
 foreach (var item in x)
 {
   var str = item.Value.Split('-')[0];
   if (counter == 0)
      counter = Convert.ToInt16(new Regex(@"\d+$").Match(str).Value) - 1;
   dict.Add("deqn" + (counter++).ToString(), item.Value);
 }

真正的工作代码是:

int counter = 0;
Dictionary<string, string> dict = new Dictionary<string, string>();
XDocument doc = XDocument.Load(@"C:\Practice\test.xml", LoadOptions.PreserveWhitespace);
Regex reg = new Regex(@"deqn(\d+)-(\d+)");
(from y in doc.Descendants("disp-formula").ToList()
         where reg.IsMatch(y.Attribute("id").Value)
         select y.Attribute("id")).ToList().ForEach(item=>
          {

            if (counter == 0)
                 counter = Convert.ToInt16(new Regex(@"\d+$").Match(item.Value.Split('-')[0]).Value) - 1;
                 dict.Add("deqn" + (++counter).ToString(), item.Value);
});

【讨论】:

  • 我收到一个错误System.ArgumentException: An item with the same key has already been added.
  • 是的,示例只是一个示例,因为 item.Name 将是 id 并且它是重复的,您可以尝试最后一个截断的代码。
  • 您的代码将密钥作为 "deqn1", "deqn2" 提供,它应该是 "deqn2", "deqn3", "deqn4", "deqn5", "deqn6", "deqn8", "deqn9", "deqn10" 。也许你误解了要求。不管怎样,谢谢你分享你的方法..:)
  • 不,它真的是做你想做的,你在我上次编辑之前测试过,那是因为++优先级,你只是测试一下,我的代码很复杂。
【解决方案4】:

这是我想要构建的最终程序

string[] path=Directory.GetDirectories(textBox1.Text,"xml",SearchOption.AllDirectories)
                .SelectMany(x=>Directory.GetFiles(x,"*.xml",SearchOption.AllDirectories)).ToArray();
            Dictionary<string, string> dict = new Dictionary<string, string>();
            var regex = new Regex(@"deqn(\d+)-(\d+)");
            foreach (var file in path) {
                dict.Clear();
                XDocument doc = XDocument.Load(file, LoadOptions.PreserveWhitespace);
                var x = from y in doc.Descendants("disp-formula")
                    let m = regex.Match(y.Attribute("id").Value)
                    where m.Success
                    select m;
                foreach (var item in x)
                {
                    var from = int.Parse(item.Groups[1].Value);
                    var to = int.Parse(item.Groups[2].Value);
                    for (int i = from; i <= to; i++)
                        dict.Add("rid=\"deqn" + i+"\"", "rid=\""+item.Value+"\"");

                    foreach (KeyValuePair<string,string> element in dict) {
                        string text=File.ReadAllText(file);
                        text=text.Replace(element.Key,element.Value);
                        File.WriteAllText(file, text);
                    }

                }
            }
            MessageBox.Show("Done");

感谢@lomed 和@Mike Mat 在这方面帮助我...:)

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 2022-10-12
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多