简体   繁体   中英

What is the best way to compare two list of complex object in c#

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}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM