[英]c# - How to remove matching items from a list using Linq or otherwise
我正在嘗試從列表中刪除匹配的項目,這似乎是一項非常簡單的任務,但幸運的是,我無法弄清楚。
示例列表:
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 }
“群策群力”來救援!
這是一個 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.