繁体   English   中英

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

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

我正在尝试从列表中删除匹配的项目,这似乎是一项非常简单的任务,但幸运的是,我无法弄清楚。

示例列表:

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

我试图让uniquePoints11,2

我知道有.Distinct()但这会返回1,2,3这不是我想要的。

我还尝试了以下与.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);

任何帮助或方向表示赞赏。

您可以使用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 }

“群策群力”来救援!

这是一个 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