LINQ checking for duplicate objects (excluding ID)

2019-06-04 00:07发布

问题:

I am using LINQ to SQL (SQL Server) with C#.

I have a table called "Cars" which automatically becomes the LINQ class/object called "Car". All well and good.

Each car has a number of fields, say CarID(primary key int), EngineID, ColourID.

I have 10 existing rows in the Cars table.

Using all the cool LINQ stuff, I create a new "Car" object in C# with an overloaded constructor that I've created in my "Car" partial class. So for example:

Car MyCar = new Car(17, 5);

Now this nicely gives me a reference to a new Car object, which I of course haven't yet committed to the database.

What is the most LINQ-savvy/latest way to run a quick check to ensure that no other cars with the same EngineID and ColourID values exist (I don't care if they have a different CarID - I just want to compare the other value columns and ensure that I don't create and insert any more cars with the same Engine/Colour combination).

Is there a cool way to achieve this really quickly with something like:

return db.Cars.Equals(x => MyCar);

回答1:

You can use .Distinct with an IEqualityComparer

var distinctcars = from Repo.cars.Distinct(new MyComparer());

A good example of an IEqualityComparer is here - http://msdn.microsoft.com/en-us/library/bb338049.aspx

If you check out the ProductComparer example, all you'd probably need to do is replace the "Check whether the products' properties are equal" part with the check you want to make and that's pretty much it.