简体   繁体   English

C# 列表 - 删除重复项

[英]C# List - Remove duplicates

I have a list that look like this:我有一个看起来像这样的列表:

U-70754, U-70755
U-70754, U-70755
U-70754, U-70755, U-70786, U-70787, U-70788
U-70754, U-70755, U-70786, U-70787, U-70788
U-70754, U-70755, U-70786, U-70787, U-70788
U-70754, U-70755, U-70786, U-70787, U-70788

I looking for a way to remove duplicates, and rearrange the list so the list will look like this:我正在寻找一种删除重复项的方法,并重新排列列表,使列表如下所示:

U-70754
U-70755
U-70786
U-70787
U-70788

I can't seem to wrap my head around this issue, I hope someone can help.我似乎无法解决这个问题,希望有人能提供帮助。

Thanks in advance!提前致谢!

You can split every item by comma, map the result into one sequence using SelectMany , then use Distinct method to get a unique values您可以使用逗号将每个项目拆分为 map 使用SelectMany将结果分成一个序列,然后使用Distinct方法获取唯一值

var list = new List<string>
{
    "U-70754, U-70755",
    "U-70754, U-70755",
    "U-70754, U-70755, U-70786, U-70787, U-70788",
    "U-70754, U-70755, U-70786, U-70787, U-70788",
    "U-70754, U-70755, U-70786, U-70787, U-70788",
    "U-70754, U-70755, U-70786, U-70787, U-70788"
};

var result = list.SelectMany(i => i.Split(new [] { ',' })).Distinct().ToList();

If I'm understanding the structure of your list correctly, it looks like each item can contain several comma-separated strings.如果我正确理解列表的结构,看起来每个项目都可以包含几个逗号分隔的字符串。 If that's the case, you can get what you're looking for with a few extra lines:如果是这种情况,您可以通过一些额外的行来获得所需的内容:

var filteredList = list.SelectMany(x => x.Split(","))
                       .Select(x => x.Trim())
                       .Distinct()
                       .OrderBy(x => x);

Here's a .NET Fiddle showing it in action.这是一个 .NET Fiddle展示了它的实际应用。

EDIT : I see Pavel beat me to the punch with essentially the same answer, but this code Trim s the Split strings (without which they won't sort correctly) and then explicitly orders them since Distinct will most likely only preserve the original order.编辑:我看到 Pavel 以基本相同的答案击败了我,但是这段代码Trim是 Split 字符串(没有它,它们将无法正确排序),然后显式地对它们进行排序,因为Distinct很可能只保留原始顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM