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

时间:2015-09-02 17:54:42

标签: c# linq

我必须使用LINQ选择不同的1000条记录。但是,当我看到生成的查询时,它需要1000条记录并对该结果应用不同。

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

我的TestClass会是什么样的,

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

有什么方法可以解决这个问题,以便将distinct应用于结果集,然后从不同的结果集中获取1000?

3 个答案:

答案 0 :(得分:1)

区别将在拍摄前处理。仔细检查您的Distinct是否正常运行。这是一个有效的例子:

ICSharpCode.Decompiler

我怀疑你的问题是在SQL上使用distinct。如果是这种情况,您还可以使用分组来获得所需的结果。

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`

答案 1 :(得分:0)

即使您在Take()之前执行distinct(),您只需要记录1000条记录,然后使用代码对这1000条记录应用distinct。

实现此目的的最佳方法是直接从SQL查询中获取1000条不同的记录,而不是从代码I.E

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

答案 2 :(得分:-1)

您可以使用嵌套的linq查询

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