[英]How can i group list-items using a data attribute?
How can i group a List Items based data attribute data-group?如何对基于列表项的数据属性数据组进行分组? I am trying to avoid duplicate in my list based on the following conditions.我试图根据以下条件避免在我的列表中重复。
My Conditions are:我的条件是:
PartyName
and SubPartyName
appears multiple times I want to merge them如果 Same PartyName
和SubPartyName
出现多次我想合并它们PartyName
but different subPartyName
group by PartyName
.如果相同的PartyName
但不同的subPartyName
组由PartyName
。Below is my code to create a list:以下是我创建列表的代码:
<ul id="list">
@foreach (var item in Info){
<li data-group="@item.PartyName" data-expanded="true"> @item.PartyName
<ul>
<li data-group="@item.SubPartyName" data-expanded="true">@item.subPartyName</li>
</ul>
</li>
}</ul>
My current list looks like as shown below:我当前的列表如下所示:
Party A甲方
Party A 甲方
- SubParty A甲方
Party A 甲方
- SubParty B乙方
Party A 甲方
- SubParty B乙方
Party B 乙方
Party C 方C
I Would like to see my list as:我希望看到我的清单:
Party A 甲方Party B 乙方
- SubParty A甲方
- SubParty B乙方
Party C 方C
You can do like this你可以这样做
public class InfoClass
{
public string PartyName { get; set; }
public string SubPartyName { get; set; }
}
public class NewInfoClass
{
public string PartyName { get; set; }
public List<string> SubPartyName { get; set; }
}
Controller Action Controller 动作
public ActionResult Index()
{
List<InfoClass> infos = new List<InfoClass>();
infos.Add(new InfoClass() { PartyName = "Party A", SubPartyName = "SubParty A" });
infos.Add(new InfoClass() { PartyName = "Party A", SubPartyName = "SubParty B" });
infos.Add(new InfoClass() { PartyName = "Party A", SubPartyName = "SubParty B" });
infos.Add(new InfoClass() { PartyName = "Party A" });
infos.Add(new InfoClass() { PartyName = "Party B" });
infos.Add(new InfoClass() { PartyName = "Party C" });
var results = from p in infos
group p.SubPartyName by p.PartyName into g
select new { PartyName = g.Key, SubPartyNames = g.ToList().Distinct() };
List<NewInfoClass> newList = new List<NewInfoClass>();
int count = 0;
foreach (var item in results)
{
newList.Add(new NewInfoClass()
{
PartyName = item.PartyName,
});
newList[count].SubPartyName = new List<string>();
foreach (var item2 in item.SubPartyNames)
{
if (item2 != null)
{
newList[count].SubPartyName.Add(item2);
}
}
count++;
}
return View(newList);
}
View看法
@model List<DemoApplication.Models.NewInfoClass>
<ul id="list">
@foreach (var item in Model)
{
<li data-group="@item.PartyName" data-expanded="true">
@item.PartyName
@foreach (var item2 in item.SubPartyName)
{
<ul>
<li data-group="@item2" data-expanded="true">@item2</li>
</ul>
}
</li>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.