Ok, this looks ugly 🙂 What is a good way to refactor this block of code?
Users is data which is entered on the screen, and for this example we want distinct result in the _someDTOObject.Users
string[] userNames = Users.Split(new char[] { ',' });
string tempUserStr = "";
foreach (string user in userNames)
{
tempUserStr += user.Trim().ToUpper() + ",";
}
userNames = tempUserStr.Split(new char[] { ',' });
var uniqueUsers = userNames.Distinct().ToList();
foreach (string user in uniqueUsers)
{
if (!string.IsNullOrEmpty(user))
{
_someDTOObject.Users += user + ",";
}
}
It looks like you probably want something like:
… but it’s not clear to me why you’re going through split/join/split to start with…
Note: if you’re using .NET 3.5, you’ll need an extra
ToArraycall afterDistinct. You don’t on .NET 4, as the set ofstring.Joinoverloads has been increased.(As noted in StriplingWarrior’s answer, this won’t have a trailing comma. Did you want a trailing comma?)