很抱歉有很长的说明,但我想让用户了解我的问题很简单。
我有一个包含DepartmentItem
和EmployeeItem
的列表。
var empSubRelList = new List<EmpDeptRel>();
internal class EmpDeptRel
{
public Item DepartmentItem { get; set; }
public Item EmployeeItem { get; set; }
}
以下是解释我如何向列表中添加项目的代码:
Item userProfile = Sitecore.Context.Database.GetItem("/sitecore/content/Intranet/User Profiles");
foreach (var subRelItem in userProfile.Axes.GetDescendants().Where(p => p.TemplateID.ToString() == Settings.GetSetting("SubRelTemplateID")
&& p["Subsidiary"] == SubssdiaryItem.ID.ToString()).OrderBy(p => p["Department"]))
{
empSubRelList.Add(new EmpDeptRel
{
DepartmentItem = GetItemById(subRelItem["Department"]),
EmployeeItem = subRelItem.Parent.Parent
});
}
我用转发器绑定它:
repEmployees.DataSource = empSubRelList;
repEmployees.DataBind();
<asp:Repeater runat="server" ID="repEmployees">
<ItemTemplate>
<li>
<%# Name(Eval("DepartmentItem") as Item)%>
<%# Name(Eval("EmployeeItem") as Item)%>
</li>
</ItemTemplate>
以下是转发器
中方法“Name()
”的代码
protected string Name(Item item)
{
if (item != null)
{
return item.Name;
}
return string.Empty;
}
输出是:
IT TestUser1
Administration TestUser2
Administration TestUSer3
Administration TestUser4
Administration TestUser5
Finance TestUSer6
是否有可能将列表“empSubRelList”与Department分组以便我可以得到以下输出:
IT TestUser1
Administration TestUser2 TestUser3 TestUser4 TestUser5
Finance TestUser6
答案 0 :(得分:1)
这应该这样做:
var list = new List<CustomItem>(){
new CustomItem() { Department= "IT", UserName = "TestUser1"},
new CustomItem() { Department = "Administration", UserName = "TestUser2"},
new CustomItem() { Department = "Administration", UserName = "TestUser3"},
new CustomItem() { Department = "Administration", UserName = "TestUser4"},
new CustomItem() { Department = "Administration", UserName = "TestUser5"},
new CustomItem() { Department = "Finance", UserName = "TestUser6"},
};
list.GroupBy (l => l.Department)
.Select (l => new {
Department = l.Key,
Users = l.Select (x => x.UserName).Aggregate ((c,n) => c + ", " + n )
});
输出继电器:
他们关键的是,您首先按部门项目分组。之后,您选择用户名属性并对其进行聚合。
Aggregate()
所做的是,它接受当前(c
)和下一个(n
)项,然后执行您使用它们指定的内容。在这种情况下,它用逗号和空格连接它们((c,n) => c + ", " + n)
。然后它移动到下一个项目
答案 1 :(得分:1)
正如Serv所写,您可以在设置转发器的数据源之前进行分组:
IEnumerable<KeyValuePair<string, string>> dataSource = empSubRelList
.GroupBy(listItem => Name(listItem.DepartmentItem))
.Select(grouping => new KeyValuePair<string, string>(
groupping.Key,
string.Join(", ", grouping.Select(emp => Name(emp.EmployeeItem)))
));
repEmployees.DataSource = dataSource;
然后在你的HTML代码中:
<asp:Repeater runat="server" ID="repEmployees">
<ItemTemplate>
<li>
<%# ((KeyValuePair<string, string>)Container.DataItem).Key %>
<%# ((KeyValuePair<string, string>)Container.DataItem).Value %>
</li>
</ItemTemplate>
</asp:Repeater>