简体   繁体   English

c# - 如何使用 Linq 或其他方式从列表中删除匹配项

[英]c# - How to remove matching items from a list using Linq or otherwise

I'm trying to remove matching items from a list, which seems like a pretty simple task, but as luck would have it, I can't figure it out.我正在尝试从列表中删除匹配的项目,这似乎是一项非常简单的任务,但幸运的是,我无法弄清楚。

Example list:示例列表:

List<int> points1 = new List<int>
{
    1, 2, 3, 3
};

I'm trying to get uniquePoints1 to be 1,2我试图让uniquePoints11,2

I know there is .Distinct() but that would return 1,2,3 which is not what I want.我知道有.Distinct()但这会返回1,2,3这不是我想要的。

I've also tried the following along with .Distinct() but I get a red line saying Comparison made to the same variable, did you mean to compare to something else?我还尝试了以下与.Distinct()但我得到一条红线,上面写着Comparison made to the same variable, did you mean to compare to something else?

List<int> uniquePoints1 = points1.Where(x => x == x);
List<int> uniquePoints1 = points1.RemoveAll(x => x == x);

Any help or direction is appreciated.任何帮助或方向表示赞赏。

You can use the GroupBy method to group the items, and then return only the numbers from groups that have a count of 1 :您可以使用GroupBy方法对项目进行分组,然后仅返回计数为1组中的数字:

List<int> uniquePoints = points
    .GroupBy(x => x)              // Group all the numbers
    .Where(g => g.Count() == 1)   // Filter on only groups that have one item
    .Select(g => g.Key)           // Return the group's key (which is the number)
    .ToList();

// uniquePoints = { 1, 2 }

"Group by" to the rescue! “群策群力”来救援!

This is a LINQ variant -- see other answers for a non-LINQ version这是一个 LINQ 变体——请参阅非 LINQ 版本的其他答案

var nonDuplicatedPoints = from p in points1
                          group p by p into g 
                          where g.Count() == 1
                          select g.Key;

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

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