如何从C#中的列表中删除非重复项

时间:2021-11-26 21:48:38

I want to do the opposite thing as here

我想做与此相反的事情

I have a list and I know how to remove the duplicates. But I want to have an option where the user can select which duplicate to keep. Some query quere I can have a list that will only show the duplicates. Something like:

我有一个列表,我知道如何删除重复项。但是我希望有一个选项,用户可以选择要保留的副本。一些查询问题我可以有一个只显示重复项的列表。就像是:

Lets say my list is:

让我们说我的清单是:

"tom" "bob" "Frank" "bob" "Lacey" "Frank"

“tom”“bob”“Frank”“bob”“Lacey”“Frank”

I know that if I use the distinct method I will get:

我知道如果我使用不同的方法,我会得到:

"tom" "bob" "Frank" "Lacey"

“汤姆”“鲍勃”“弗兰克”“莱西”

I don't know what method to I have to use to get:

我不知道我必须使用什么方法来获取:

"bob" "bob" "frank" "frank"

“bob”“bob”“frank”“frank”

or to get

或得到

"bob" "frank"

“bob”“frank”

cause those are the ones that repeat.

因为那些是重复的。

2 个解决方案

#1


22  

You can use GroupBy to filter out the items that only occur once, then flatten the remaining items back into a list:

您可以使用GroupBy过滤掉仅出现一次的项目,然后将其余项目展平回列表:

var resultList = list.GroupBy(x => x)
                     .Where(g => g.Count() > 1)
                     .SelectMany(g => g)
                     .ToList();

#2


1  

I needed to compare them by a specific property theretofore I just modified your query BrokenGlass to

我需要通过一个特定的属性来比较它们,我刚才修改了你的查询BrokenGlass

var resultList = itemsThatNeedToBeAdded.GroupBy(x => x.property1)
                     .Where(g => g.Count() > 1 )
                     .SelectMany(g => g)
                     .ToList();

#1


22  

You can use GroupBy to filter out the items that only occur once, then flatten the remaining items back into a list:

您可以使用GroupBy过滤掉仅出现一次的项目,然后将其余项目展平回列表:

var resultList = list.GroupBy(x => x)
                     .Where(g => g.Count() > 1)
                     .SelectMany(g => g)
                     .ToList();

#2


1  

I needed to compare them by a specific property theretofore I just modified your query BrokenGlass to

我需要通过一个特定的属性来比较它们,我刚才修改了你的查询BrokenGlass

var resultList = itemsThatNeedToBeAdded.GroupBy(x => x.property1)
                     .Where(g => g.Count() > 1 )
                     .SelectMany(g => g)
                     .ToList();