替代c#foreach循环从列表中获取项目

时间:2018-09-21 06:09:39

标签: c# asp.net-mvc arraylist foreach

我希望有人可以帮助解决这个简单的问题。我已经寻找了答案,但我认为部分问题是我不完全知道自己要问的问题。我有以下代码。

@using System;
@using System.Collections.Generic;
@using System.Linq;
@using System.Xml.Linq;

<div>
@{ 
  String URLString = "https://api3.libcal.com/api_hours_grid.php?iid=4246&  format=xml&weeks=1&systemTime=0";
  XDocument xdoc = new XDocument();
  xdoc = XDocument.Load(URLString);


  var location = (from p in xdoc.Descendants("location")
                  from s in p.Descendants("week").Elements()
                  select new
                  {                  
                      CampusName = (string)p.Element("name"),
                      WeekD = (string)s.Element("date")
                  }).ToList();


                  foreach (var item in location)

                  {
                     foreach (var item in location)
                     {
                     <p>@item.WeekD</p>
                     }

                    <h2>@item.CampusName</h2>

                  }
}

</div>

显然,嵌套的foreach循环会导致错误。我想要实现的是类似以下的内容

<h2>Campus Name</h2>
<p>date</p>
<p>date</p>

<h2>Campus Name</h2>
<p>date</p>
<p>date</p>

依此类推,有人可以就我如何获得此结果提供一些建议。

3 个答案:

答案 0 :(得分:0)

(伪代码)

/usr/local/etc/

答案 1 :(得分:0)

您可以尝试GroupBy CampusName,然后将结果投影到ToDictionary,就像

@using System;
@using System.Collections.Generic;
@using System.Linq;
@using System.Xml.Linq;

<div>
    @{
        String URLString = "https://api3.libcal.com/api_hours_grid.php?iid=4246&  format=xml&weeks=1&systemTime=0";
        XDocument xdoc = new XDocument();
        xdoc = XDocument.Load(URLString);


        var location = (from p in xdoc.Descendants("location")
                        from s in p.Descendants("week").Elements()
                        select new
                        {
                            CampusName = (string)p.Element("name"),
                            WeekD = (string)s.Element("date")
                        }).ToList();


        var result = location.GroupBy(x => x.CampusName)
               .ToDictionary(grp => grp.Key, grp => grp.Select(x => x.WeekD));


        foreach (var item in result)
        {
            <h2>@item.Key</h2>
            foreach (var innerItem in item.Value)
            {
                <p>@innerItem</p>
            }
        }
    }

</div>

输出:输出包含6行位置名称,但为简单起见,此处仅显示2行

enter image description here

答案 2 :(得分:0)

我为您编写了代码。试试吧!

    string URLString = "https://api3.libcal.com/api_hours_grid.php?iid=4246&%20format=xml&weeks=1&systemTime=0";
    XDocument xdoc = XDocument.Load(URLString );

    foreach (var element in xdoc.Descendants("location"))
    {
        var temp = element.Descendants("name");
        string name = "";
        if (temp.Count() != 0)
            name = temp.ToList()[0].Value;
        <h2>@name</h2>
        foreach (var d in element.Descendants("date"))
        {
            var date = d.Value;
            <p>date</p>
        }
    }