问题描述
我有一个整数元组列表
List<Tuple<int, int>> list = new List<Tuple<int, int>>();
list.Add(new Tuple<int, int>(1,12));
list.Add(new Tuple<int, int>(1,2));
list.Add(new Tuple<int, int>(1,18));
list.Add(new Tuple<int, int>(1,12));
在这种情况下,我想删除item2的冗余值
I want to remove the redundant value of item2 which is 12 in this case
更新后的列表也应该是列表". (相同的类型),但具有不同的值.类型为List>的新元组应仅包含以下内容:
The updated list should also be List>. (same type) but with distinct values.The new tuple of type List> should contain only following:
list.Add(new Tuple<int, int>(1,2));
list.Add(new Tuple<int, int>(1,18));
list.Add(new Tuple<int, int>(1,12));
有帮助吗?
推荐答案
如果只需要唯一的数字对,则可以使用Distinct()
轻松完成:
If you want only the unique pairs of numbers this can easily be done by using Distinct()
:
list = list.Distinct().ToList();
如果仅考虑删除 only Item2的重复项,则使用GroupBy()
和Select()
每个组的First()
:
If you only care about removing duplicates of only Item2, then use GroupBy()
and Select()
the First()
of each group:
list = list.GroupBy(x => x.Item2).Select(x => x.First());
我做了一个小提琴此处演示了这两种方法
I made a fiddle here that demonstrates both methods
编辑
从您的最新评论中,您似乎想使用我建议的第二种方法(GroupBy Item2,然后选择每个组的第一个).
From your latest comment, it sounds like you want to use the second method I have proposed (GroupBy Item2 and Select the First of each Group).
这篇关于根据C#中整数元组列表的item2进行不同的应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!