Apply distinct on the basis of item2 of List of integer tuples in c# [duplicate]

有些话、适合烂在心里 提交于 2019-12-13 09:49:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!