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

标签 c#

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

示例列表:

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/

相关文章:

c# - 使用 .NET ConfigurationManager 从字符串而不是 app.config 文件中读取设置

c# - 是否有任何适用于 ASP.NET MVC 应用程序的开源 Comet Web 服务器?

c# - 带有 CaSTLe Windsor 的 Nlog 3.1 不记录

c# - C#中的线程

c# - WPF 绑定(bind)可见性

c# - Web API 2 返回错误并让 http.post 捕获它

c# - 将 Entity Framework 模型映射到多个表

C# 与嵌套类有关系

c# - 无法在 ASP.NET Core 2 中序列化为 XML

c# - 列出多个组下的 API 方法