0

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?

5
  • 1
    Do you only care about the second tuple value? Meaning, thats the only one you need to distinct on? Or only duplicate matches of item1 and item2? Commented Oct 11, 2017 at 16:51
  • so thats the problem i need both values i.e i want the tuple of the same type with both the values Commented Oct 11, 2017 at 16:55
  • that comment makes no sense. What happens if you have a Tuple with (2,12), should that be part of your output since the first value is unique or should it be excluded because the second value is a duplicate? Commented Oct 11, 2017 at 16:58
  • i want to retain both the values item1 and item2 in the new tuple but i have to apply distinct on the basis of item2. Acc. to the above example one 2,12 will be removed because item2 12 is 2 times. So my new tue will contain 3 values instead of 4 Commented Oct 11, 2017 at 17:06
  • Then the second part of my answer is what you are looking for. Commented Oct 11, 2017 at 17:07

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.