Please help me to fix this issue. My dropdown list looks something like this mentioned below.
- Client
- Contractor,Contractor,Contractor,Manager
- Contractor,Manager
- Manager
- Operator
- Viewer
I want to remove the duplicates and my output should be like :
- Client
- Contractor
- Manager
- Operator
- Viewer
This is my code mentioned below:
Property:
public List<string> TeamRoleNames => TeamRoleUids.Select(MainRoles.GetRoleName).ToList();
Display Method:
{
result += " ; TeamRoleNames=" + this.TeamRoleNames;
}
GetRole Method:
{
string roleName;
if (RoleNameByUid.TryGetValue(roleUid, out roleName))
{
return roleName;
}
return null;
}
I have tried with Distinct Method mentioned below, But did not work like the output what I wanted!
public List<string> TeamRoleNames => TeamRoleUids.Select(MainRoles.GetRoleName).Distinct().ToList();
How can I fix this? Can anyone help?
4
Answers
Consider converting the list to a set (hashset) since sets as a data structure doesn’t allow duplicates.
More about hashsets form official documentation.
So, the solution would be similar to the following:
example:
then converting it back toList() will remove duplicates.
If you have already tried
Distinct
and it hasn’t worked, then you could do the following;Split your string list to a
List<string>
Then when you’re adding them to the dropdwon, check to see if the role is already in the dropdown. If so, move on, else add to the dropdown.
So something like
Having elements comma separated require you to split them first to have an homogenous collection then do the distinct
You can use
SelectMany
to flatten a enumeration containing a nested enumeration. Here, we create the nested enumeration by splitting the string at the commas:prints