LINQ 检查重复对象(不包括 ID)

发布于 2024-09-11 02:58:25 字数 596 浏览 2 评论 0原文

我正在使用 LINQ to SQL (SQL Server) 和 C#。

我有一个名为“Cars”的表,它自动成为名为“Car”的 LINQ 类/对象。 一切都很好。

每辆车都有许多字段,例如 CarID(primary key int)、EngineID、ColourID。

我的 Cars 表中有 10 行。

使用所有很酷的 LINQ 东西,我在 C# 中创建了一个新的“Car”对象,其中包含我在“Car”部分类中创建的重载构造函数。举例来说:

Car MyCar = new Car(17, 5);

现在这很好地为我提供了对新 Car 对象的引用,当然我还没有将其提交到数据库。

运行快速检查以确保不存在具有相同 EngineID 和 ColourID 值的其他汽车(我不关心它们是否有不同的 CarID - 我只想比较其他值)最精通 LINQ/最新的方法是什么列并确保我不会创建和插入更多具有相同引擎/颜色组合的汽车)。

有没有一种很酷的方法可以通过以下方式快速实现这一目标:

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

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赢得她心 2024-09-18 02:58:25

您可以将 .Distinct 与 IEqualityComparer 结合使用

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

IEqualityComparer 的一个很好的示例在这里 - http://msdn.microsoft.com/en-us/library/bb338049.aspx

如果您查看 ProductComparer 示例,您可能需要做的就是替换“检查产品的性能是否相同”部分与您想要进行的检查有关,仅此而已。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文