简体   繁体   English

使用Linq到XML时返回分组项目的值

[英]Returning Value of Grouped Items when using Linq to XML

I am trying to use Linq to XML in Visual Studio - C# to pull all of the Elements in an XML file and group them by their value. 我正在尝试在Visual Studio-C#中使用Linq到XML,以将XML中的所有元素拉出并按它们的值分组。

This is my XML code: 这是我的XML代码:

<?xml version="1.0" encoding="utf-8"?>
 <topTerms>
   <topTerm>Cat</topTerm>
  <topTerm>Dog</topTerm>
  <topTerm>Cat</topTerm>
  <topTerm>Dog</topTerm>
  <topTerm>Cat</topTerm>
  <topTerm>Bird</topTerm>
  <topTerm>Cat</topTerm>
</topTerms>

I am then using the following C# code to try and pull the data and group it by value of the topTerm element. 然后,我使用以下C#代码尝试提取数据并按topTerm元素的值对其进行分组。

var top = 0;
        var topName = "";
        var topTermsUrl = Server.MapPath("XML/topTerms.xml");
        XDocument topTermsFile = XDocument.Load(topTermsUrl);
        var topTermDocuments = topTermsFile.Root
                        .Elements("topTerm")
                        .GroupBy(a => a.Value);
    foreach (var topTerm in topTermDocuments)
    {
        topName = topTerm.Value;
        top = topTerm.Count();
    }

However, topTerm.Value is not working. 但是,topTerm.Value不起作用。 It will count the number of occurrence for each value when I cycle through, but I cannot get the string value being counted. 当我循环遍历时,它将计算每个值的出现次数,但无法获取正在计算的字符串值。 Any ideas? 有任何想法吗?

topTerm is an IGrouping , particularly IGrouping<string, XElement> . topTerm是一个IGrouping ,尤其是IGrouping<string, XElement> So it has a property Key that contains the value by which you grouped: 因此,它具有一个属性Key ,其中包含您进行分组的值:

foreach (var topTerm in topTermDocuments)
{
    topName = topTerm.Key; // Key used here
    top = topTerm.Count();
}

(I assume that in the full code you do more than overwriting variables in a loop). (我认为在完整的代码中,您要做的不仅仅是覆盖循环中的变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM