LINQ检查重复的对象(不包括ID) [英] LINQ checking for duplicate objects (excluding ID)

查看:142
本文介绍了LINQ检查重复的对象(不包括ID)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有C#的LINQ to SQL(SQL Server)。



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



每辆车都有多个字段,说CarID(主键int),EngineID,ColourID。



我在Cars表中有10个现有行。



使用所有酷LINQ的东西,我创建一个新的Car对象C#与我在Car部分类中创建的重载构造函数。所以例如:

  Car MyCar = new Car(17,5); 

现在这很好地给了我一个新的Car对象的引用,我当然还没有致力于数据库。



最新的LINQ-精明/最新的方法是运行快速检查,以确保没有其他车辆具有相同的EngineID和ColourID值存在(我不在乎他们是否有不同的CarID - 我只是想比较其他值列,并确保我不创建和插入任何更多的汽车与相同的引擎/颜色组合)。



有一个很酷的方法来实现这一点,真的很快,如下所示:

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


解决方案

您可以使用.Distinct与 IEqualityComparer

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

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



如果您查看ProductComparer示例,您可能需要做的只是替换检查产品的属性是否相等,其中包含您想要的支票,这几乎是。


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

解决方案

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.

这篇关于LINQ检查重复的对象(不包括ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆