Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a Distinct IQueryable with LINQ?

Tags:

c#

linq

distinct

I'm writing a Function that pulls Records from a DataBase using LINQ to get an IQueryable. This LINQ statement will pull all of the records for Active users within a certain time period, and then spit the UserID, First Name, and Last Name out to a Telerik RadGrid.

My problem lies within trying to get a Distinct Value on the UserID when pulling this Data. I have tried re-working this code to get my result. Here is the an example of the code that is pulling all of the Data, with the Distinct NOT working.

public static IQueryable GetActiveEmployees_Grid(string Period)
{
    DataContext Data = new DataContext();
    var Employees = (from c in DataSystem_Records
                     where c.Period == Period
                     orderby c.DataSystem_Employees.LName
                     select c).Distinct();

    return Employees;
}

After applying the DataSource to my Grid, this returns the User 4 times, one instance for each Record for that Period.

alt text

Is there a way to apply Distinct to my LINQ Function to make this work the way I intend it to?

like image 485
Lando Avatar asked Dec 17 '10 16:12

Lando


3 Answers

Simplest way I have found to do this with object is using the groupby then selecting the first.

public static IQueryable GetActiveEmployees_Grid(string Period)
{
    DataContext Data = new DataContext();
    var Employees = (from c in DataSystem_Records
                     where c.Period == Period
                     orderby c.DataSystem_Employees.LName
                     select c).GroupBy(g=>g.DataSystem_Employees.AccID).Select(x=>x.FirstOrDefault());

    return Employees;
}

This is not tested but the general concept is there.

Edit: I remembered originally finding the answer somewhere on here. Check out this for grouping objects by a certain property. LINQ's Distinct() on a particular property

like image 93
Gage Avatar answered Oct 14 '22 20:10

Gage


If you limit the objects you are returning to only the fields that you want to display, it will work properly.

public static IQueryable GetActiveEmployees_Grid(string Period)
{
    DataContext Data = new DataContext();
    var Employees = (from c in DataSystem_Records
                     where c.Period == Period
                     orderby c.DataSystem_Employees.LName
                     select c.DataSystem_Employees.FName, 
                            c.DataSystem_Employees.LName, 
                            c.ID).Distinct();

    return Employees;
}
like image 44
sgriffinusa Avatar answered Oct 14 '22 22:10

sgriffinusa


try and write an IEqualityComparer<T> for the object type being selected and use it in your Distinct method

like image 21
Dean Chalk Avatar answered Oct 14 '22 22:10

Dean Chalk