0
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

我尝试进一步澄清我的代码..

4

2 回答 2

1

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

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

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

于 2012-10-02T06:01:54.413 回答
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);
于 2012-10-02T06:11:29.673 回答