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?
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).
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With