Sorry for the long description but I want to make it simple for the users to understand my problem.
I have a list that contains DepartmentItem
and EmployeeItem
.
var empSubRelList = new List<EmpDeptRel>();
internal class EmpDeptRel
{
public Item DepartmentItem { get; set; }
public Item EmployeeItem { get; set; }
}
Here is the code that explains how I am adding items to the list:
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
});
}
I bind it with a repeater:
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>
Here is the code for the method "Name()
" which is inside the repeater
protected string Name(Item item)
{
if (item != null)
{
return item.Name;
}
return string.Empty;
}
the Output is:
IT TestUser1
Administration TestUser2
Administration TestUSer3
Administration TestUser4
Administration TestUser5
Finance TestUSer6
Is it somehow possible to group the list "empSubRelList" With Department So that I can get following output:
IT TestUser1
Administration TestUser2 TestUser3 TestUser4 TestUser5
Finance TestUser6
As Serv wrote, you can do grouping before setting the datasource of your repeater:
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;
and then in your html code:
<asp:Repeater runat="server" ID="repEmployees">
<ItemTemplate>
<li>
<%# ((KeyValuePair<string, string>)Container.DataItem).Key %>
<%# ((KeyValuePair<string, string>)Container.DataItem).Value %>
</li>
</ItemTemplate>
</asp:Repeater>