简体   繁体   English

linq查询Take()优先于Distinct()?

[英]linq query Take() takes precedence over Distinct()?

I have to select distinct 1000 records using LINQ. 我必须使用LINQ选择不同的1000条记录。 But when I see the query generated it takes 1000 records and applies distinct over that result. 但是当我看到生成的查询时,它需要1000条记录并对该结果应用不同的记录。

IQueryable<TestClass> resultSet = (from w in ......).Distinct().Take(1000);

where my TestClass would be like, 我的TestClass会是什么样的,

public TestClass
{
public string TestPRop { get; set; }
 //..has some 20 properties
}

Any way to solve this to get distinct applied to the resultset and then take 1000 from the distinct result set? 有什么方法可以解决这个问题,以便将distinct应用于结果集,然后从不同的结果集中获取1000?

Distinct will be processed before the take. 区别将在拍摄前处理。 Double check your Distinct is performing correctly. 仔细检查您的Distinct是否正常运行。 Here's a working example: 这是一个有效的例子:

var dataset = new int[]
{
    1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10
};

var query = from o in dataset select o;
var result = query.Distinct().Take(6);

// result = `1,2,3,4,5,6`

I suspect your issue is with using distinct with SQL. 我怀疑你的问题是使用与SQL的distinct。 If that is the case, you can also use grouping to get the result you want. 如果是这种情况,您还可以使用分组来获得所需的结果。

var distinctById = from o in query
                   group o by o.Id into uniqueIds
                   select uniqueIds.FirstOrDefault();

You are only taking 1000 records and then applying distinct over those 1000 records with you code even though you are doing distinct() before Take(). 即使您在Take()之前执行distinct(),您只需要记录1000条记录,然后使用代码对这1000条记录应用distinct。

The best way to accomplish this is to get the 1000 distinct records directly from your SQL query rather than from the code IE 实现此目的的最佳方法是直接从SQL查询中获取1000个不同的记录,而不是从代码IE中获取

string queryString = "SELECT top 1000 from (select distinct ... from table)";

您可以使用嵌套的linq查询

IQueryable<TestClass> resultSet = from x in ((from w in ......).Distinct()).Take(1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM