Here I have a list from my class Assinantes
new Assinante
{
City= "BAURU",
Num= 112,
ClientCode= 3123,
Phone= "1412345675"
},
new Assinante
{
City= "BAURU",
Num= 45,
ClientCode= 3123,
Phone= "214464347"
}
And I needed to group by City, ClientCod and Num, which I've already done here:
var listGroup= (from a in lista
group a by new {a.City, a.ClientCode, a.Num});
Then, I needed to generate an html string with Linq, like the example below:
<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>
Could somebody give me any sugestion?
You can use linq to xml for this issue, also included in the example options to add attributes, which could possibly be useful in the future (styling or querying)
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)
)
)
)
)
)
)
);
To get the actual string just use html.ToString()
see fiddle here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With