我正在尝试从列表中删除匹配项,这似乎是一项非常简单的任务,但幸运的是,我无法弄清楚。
示例列表:
List<int> points1 = new List<int>
{
1, 2, 3, 3
};
我试图让 uniquePoints1
成为 1,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 }
关于c# - 如何使用 Linq 或其他方式从列表中删除匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64883597/