这里我有一个来自我的班级Assinantes的列表
new Assinante
{
City= "BAURU",
Num= 112,
ClientCode= 3123,
Phone= "1412345675"
},
new Assinante
{
City= "BAURU",
Num= 45,
ClientCode= 3123,
Phone= "214464347"
}
我需要按城市,ClientCod和Num分组,我已经在这里完成了:
var listGroup= (from a in lista
group a by new {a.City, a.ClientCode, a.Num});
然后,我需要使用Linq生成一个html字符串,如下例所示:
<div>
<h2>Bauru</h2>
<ul>
<li>3123</li>
<ul>
<li>112</li>
<ul>
<li>1412345675</li>
</ul>
<li>45</li>
<ul>
<li>214464347</li>
</ul>
</ul>
</ul>
</div>
有人可以给我任何消化吗?
答案 0 :(得分:2)
您可以使用linq to xml来解决此问题,也可以在示例选项中添加属性,这可能在将来有用(样式或查询)
var html = new XElement("div", new XAttribute("class","dynamic-content"),
from i in lst.GroupBy(x=>new{x.City,x.ClientCode,x.Num}) select
new XElement("div",new XAttribute("class","city"),
new XElement("h1",new XAttribute("class","city-name"), i.Key.City ),
new XElement("ul",
from k in i.GroupBy(a=>a.ClientCode) select
new XElement("li",
new XElement("h4",new XAttribute("class","client-code"), k.Key),
new XElement("ul",
from j in k.GroupBy(a=>a.Num) select
new XElement("li",
new XAttribute("class","client-num"), j.Key ,
new XElement("ul", new XAttribute("class","phone-numbers"),
from l in j select
new XElement("li", new XAttribute("class","phone-number"), l.Phone)
)
)
)
)
)
)
);
要获取实际字符串,请使用html.ToString()
请参阅小提琴here
答案 1 :(得分:1)
您可以使用XElement
生成所需的html。我想我的样本可以用Linq方法聚合重写,但由于代码更易读,我更喜欢嵌套的foreach
using System.Xml;
using System.Xml.Linq;
...
var xml = new XElement("div");
foreach(var city in lst.GroupBy(x=>x.City))
{
var cityXml = new XElement("h2", city.Key);
var cityUl = new XElement("ul");
foreach(var client in city.GroupBy(c=>c.ClientCode))
{
var clientXml = new XElement("li", client.Key);
var clientUl = new XElement("ul");
foreach(var num in client.GroupBy(cl=>cl.Num))
{
var numXml = new XElement("li", num.Key);
var numUl = new XElement("ul");
foreach(var phone in num)
{
numUl.Add(new XElement("li",phone.Phone));
}
clientUl.Add(numXml);
clientUl.Add(numUl);
}
cityUl.Add(clientXml);
cityUl.Add(clientUl);
}
xml.Add(cityXml);
xml.Add(cityUl);
}
string res = xml.ToString();