BattlFrog BattlFrog - 1 year ago 87
C# Question

How do I check for duplicates in a List<Model>

I have a model:

public class MyModel
public int GridX { get; set; }
public int GridY { get; set; }

The user will upload a list from an excel sheet that will look something like:

GridX GridY
1 3
1 2
1 4
2 2
2 1
2 1

I currently upload the excel sheet, and loop through the rows to create a List which I will then save to the db.

I have to be able to catch duplicate rows, like the the last 2 rows that have the same coordinates (2,1).

I know for a single list I can do something like:

var hasDuplicates = MyList.GroupBy(x => x.num).Any(x => x.Count() > 1);

and hasDuplicate will be true if there are duplicates in the list. I am not sure how to do this in the case of having pairs that need to be compared. Each set of coordinates should be a group but not sure how to groupby a set. I could do it in sql, but alas I have to catch it before it gets to the db.

Answer Source

Here's how - you can group by both properties by creating an anonymous type within the GroupBy:

MyList.GroupBy(x => new { GridX = x.GridX, GridY = x.GridY }).Any(x => x.Count() > 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download