Reputation: 12997
I have 3 lists which every one of them has some instance of following class:
public class Menu
{
public string Address { get; set; }
public string Name { get; set; }
public List<Menu> Childs=new List<Menu>();
}
I fill everyone of these list in code below:
public List<Menu> GetAvailableMenus(string[] roles)
{
var adminMenu = new List<Menu>();
var terminalMenu = new List<Menu>();
var gaurdMenu = new List<Menu>();
if(roles.Contains("admin"))
{
GetAdminMenus(adminMenu);
}
if (roles.Contains("terminal"))
{
GetTerminalMenus(terminalMenu);
}
if (roles.Contains("gaurd"))
{
GetGaurdMenus(gaurdMenu);
}
return adminMenu.Union(gaurdMenu).Union(terminalMenu).ToList();
}
my problem is Union action just concat these list and do nor merge them in order to remove redundant items. does anyone has any idea what should I do?
Upvotes: 0
Views: 354
Reputation: 48596
You haven't overridden Equals
or GetHashCode
for your Menu
class, so Union
has no way (except reference equality, which won't work here) to know that there are duplicates. Implementing those methods in a sensible way will make your code work.
These links might help:
Alternatively, you can just pass in your own implementation of IEqualityComparer
as another argument to the Union method.
Upvotes: 3
Reputation: 66882
If you provide an equality comparer for Union then it will be able to merge and not just concat your lists
See http://msdn.microsoft.com/en-us/library/bb358407.aspx
Update - reading your question again I'm wondering if you also want the child menu items merged too. If that's the case, then I think you will need to write some logic to do this - I don't think there's any way of using the Linq Union operator to do this nested merging.
Upvotes: 0
Reputation: 60190
Your Menu
class needs to properly implement IEquatable<>
in order to determine whether two entries are the same or not. Otherwise Union
will use the default equality, which will compare reference equality.
Upvotes: 0