LINQ checking for duplicate objects (excluding ID)

扶醉桌前 提交于 2020-01-23 18:45:49

问题


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.



来源:https://stackoverflow.com/questions/3308314/linq-checking-for-duplicate-objects-excluding-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!