Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query Take() takes precedence over Distinct()?

Tags:

c#

linq

I have to select distinct 1000 records using LINQ. But when I see the query generated it takes 1000 records and applies distinct over that result.

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

where my TestClass would be like,

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?

like image 588
Arvind897 Avatar asked Sep 02 '15 17:09

Arvind897


People also ask

How do I get distinct on a single column in LINQ?

distinct in Linq to get result based on one field of the table (so do not require a whole duplicated records from table). I know writing basic query using distinct as followed: var query = (from r in table1 orderby r. Text select r).

How does distinct work in LINQ?

LINQ Distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax. LINQ Distinct is an operator which comes under Set Operator.

How do you use take and skip in LINQ?

The Take operator is used to return a given number of rows from a database table and the Skip operator skips over a specifed number of rows in a database table. I create a data context class that has tables or a stored procedure.


1 Answers

Distinct will be processed before the take. Double check your Distinct is performing correctly. 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. 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();
like image 137
joelnet Avatar answered Oct 10 '22 08:10

joelnet