将字符串拆分为唯一列表 - 重构它
好吧,这看起来很难看:) 重构这段代码的好方法是什么?
Users
是在屏幕上输入的数据,对于此示例,我们希望在 _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 + ",";
}
}
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 + ",";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它看起来就像你可能想要这样的东西:
...但我不清楚为什么你要通过 split/join/split 开始...
注意:如果你使用 . NET 3.5 中,您需要在
Distinct
之后进行额外的ToArray
调用。在 .NET 4 上则不需要,因为string.Join
重载集已增加。(正如 StriplingWarrior 的回答所述,这不会有尾随逗号。您想要尾随逗号吗?)
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
ToArray
call afterDistinct
. You don't on .NET 4, as the set ofstring.Join
overloads has been increased.(As noted in StriplingWarrior's answer, this won't have a trailing comma. Did you want a trailing comma?)
这是一种更简洁的方式,可以大部分获得相同的结果:
但是,这不会有结尾的“,”,这可能是理想的,也可能不是。您可能还想检查一下为什么需要首先以逗号分隔的列表结尾。您是否最好传递用户名列表?
This is a much cleaner way to mostly get the same result:
However, this won't have a trailing ",", which may or may not be desirable. You may also want to examine why you need to end up with a comma-separated list in the first place. Is it possible that you'd be better off passing around a list of user names instead?
这将负责删除重复的名称和空的名称。
This will take care of removing duplicated and empty names.
我希望这会有用。
问候。
I hope this can be useful.
Regards.