问题
I have a List of integer tuple
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));
I want to remove the redundant value of item2 which is 12 in this case
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));
Any help?
回答1:
If you want only the unique pairs of numbers this can easily be done by using Distinct()
:
list = list.Distinct().ToList();
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
EDIT
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).
来源:https://stackoverflow.com/questions/46693620/apply-distinct-on-the-basis-of-item2-of-list-of-integer-tuples-in-c-sharp