循环通过Xml数据输出结果

时间:2012-10-02 05:54:21

标签: c# linq xml-parsing linq-to-xml

var runnerElement = xDox.Descendants("User")
      .SingleOrDefault(u => u.Element("Name").Value == "David");

if (runnerElement != null)
{
    var result = runnerElement.Descendants("Runners")
      .Select(a => new
        {

            Date = DateTime.Parse(a.Element("Date").Value),
            MyLength = int.Parse(a.Element("Length").Value)
            City = a.Element("City").Value,
        })
      .Where(a => a.Date >= DateTime.Parse("3/29/2012")
                && a.Date <= DateTime.Parse("8/29/2012"))

      .GroupBy(a => a.City)
      .Select(g => new {City = g.Key, Avg = g.Average(x => x.MyLength)});
}

你如何遍历这些数据,以便它可以给我一个像这样的输出

User:David
Date:3/29/2012 to 8/29/2012
Average Distance in Paris : //Data
Average Distance in Madrid: //Data

我试着更多地澄清我的代码..

2 个答案:

答案 0 :(得分:1)

你在查询中丢失了前两位信息(但无论如何它们都是硬编码的),但对于“平均距离”位,它很简单:

foreach (var item in result)
{
    Console.WriteLine("Average Distance in {0}: {1}", item.Place, item.Avg);
}

这就是你所追求的吗?显然,您需要将其放在if块中,以便result在范围内。

答案 1 :(得分:0)

要更正我以前的答案,它应该有一个方法,假设GetData带有相关输入,因此您可以使用StringBuilder来构建字符串:

public string GetData(string userName, DateTime fromDate, DateTime toDate)
{
     var userElement = xDox.Descendants("User")
            .SingleOrDefault(u => u.Element("Name").Value == userName);

    var builder = new StringBuilder();

    if (userElement != null)
    {
        var result = userElement.Descendants("Attempts")
            .Select(a => new
                {
                    Place = a.Element("Place").Value,
                    Date = DateTime.Parse(a.Element("Date").Value),
                    Distance = int.Parse(a.Element("Distance").Value)
                })

            .Where(a => a.Date >= fromDate
                        && a.Date <= toDate)

            .GroupBy(a => a.Place)
            .Select(g => new {Place = g.Key, Avg = g.Average(x => x.Distance)});

        builder.AppendFormat("User:{0}", userName);
        builder.AppendLine();

        builder.AppendFormat("Date:{0} to {1}", fromDate, toDate);
        builder.AppendLine();

        foreach (var item in result)
        {
            builder.AppendFormat("Average Distance in {0}: {1}", 
                                               item.Place, item .Avg);
            builder.AppendLine();
        }
    }

    return builder.ToString();
}

为了使用:

var fromDate = DateTime.Parse("8/30/2012");
var toDate = DateTime.Parse("10/1/2012");

string result = GetData("David", fromDate, toDate);