-1

Hello friends I want to create a method that get two list of point (object that I'm created) and return 3 list that include:

  1. Points that exist in the first and the second list.

  2. Points that exist in the first list and not exist in the second list.

  3. Points that not exist in the first and exist in the second list.

What is the best wat to do that?

Point.cs:

Public class Point {public int X; public int Y}
Lol
  • 11
  • 1
  • If you need information on set operation - https://code.msdn.microsoft.com/LINQ-Set-Operators-374f34fe. More similar answers can be found https://www.bing.com/search?q=C%23+items+exist+both+list. – Alexei Levenkov Jan 12 '16 at 17:36
  • Hope this question can answer your query. [Get list of matching objects from 3 different lists](https://stackoverflow.com/questions/72444334/get-list-of-matching-objects-from-3-different-lists) – Aԃιƚყα Gυɾαʋ Jun 01 '22 at 09:42

2 Answers2

2

First you need to create a IEqualityComparer<Point>. Then use Intersect and Except Linq methods to achieve what you want.

  1. var result = points1.Intersect(points2, yourComparer);
  2. var result = points1.Except(points2, yourComparer);
  3. var result = points2.Except(points1, yourComparer);

where points1 and points2 are your list of points.

To implement IEqualityComparer, refer this question as a start.

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 1. What is yourComparer? 2. How I convert this to List? – Lol Jan 12 '16 at 18:00
  • @Lol 1.yourComparer is the instance of the `IEqualityComparer` which you'll be creating (How to do that is the last part of my answer). 2. `var myList = points1.Intersect(points2, yourComparer).ToList();`. Just call `ToList()` in the end. – Sriram Sakthivel Jan 12 '16 at 18:03
  • Ok, Another quastion: I'm understand that Linq compare between the HashCode so I need that the method GetHash code return X value and Y value. How I do that? – Lol Jan 12 '16 at 20:03
  • @Lol This will help to understand [how to implement GetHashCode method](http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode) also [this article](https://blogs.msdn.microsoft.com/ericlippert/2011/02/28/guidelines-and-rules-for-gethashcode/) – Sriram Sakthivel Jan 13 '16 at 06:41
  • I still do not understand why I need to implement the Equal and the HashCode? Which function is used to make the comparison? – Lol Jan 13 '16 at 11:23
0

You can do multiple things.

First use System.Drawing.Point struct instead of your own class and you will be able to the comparison as well.

Second, If you have to create your own class then override Equals and GetHashCode in your class.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • I'm understand that Linq compare between the HashCode so I need that the method GetHash code return X value and Y value. How I do that? – Lol Jan 13 '16 at 06:18