鲜明的Linq对特定领域鲜明、领域、Linq

2023-09-04 00:41:21 作者:風雨桃花劫

由于:

var s = (from p in operatorList                       
    select p.ID, p.Name,p.Phone)

我怎么会只返回基于ID的不重复的记录?

How would I return the Distinct records based only on the ID?

推荐答案

您可以写一个 的IEqualityComparer 用于比较 ID 值,并将其传递到的重载Queryable.Distinct方法,但由于这是LINQ到SQL它不会对数据库的支持。你将不得不调用添加到 AsEnumerable 方法得到它的工作,但不推荐用于大量数据的,因为你将会使数据到客户端。如果你决定走这条路,你将最终获得类似的查询:

You could write an IEqualityComparer that compares the ID values and pass it into the overloaded Queryable.Distinct method, but since this is LINQ to SQL it won't be supported on the database. You would have to add a call to the AsEnumerable method to get it working, but this isn't recommended for large amounts of data because you would be bringing the data down to the client side. If you decide to go that route you will end up with a query similar to:

var query = dc.Operators.AsEnumerable().Distinct(new OperatorEqualityComparer());

另一种选择,这使得数据库做的工作,就是按 ID ,并采取每个组中的第一项:

The other option, which makes the database do the work, is to group by ID and take the first item in each group:

var query = from p in dc.Operators
            group p by p.ID into groups
            select groups.First();