返回与LINQ鲜明的IQueryable? [英] Returning a Distinct IQueryable with LINQ?

查看:173
本文介绍了返回与LINQ鲜明的IQueryable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写使用LINQ获得一个IQueryable数据库拉记录的功能。此LINQ语句将拉的所有记录活跃用户在一定时间内,然后吐了用户名,名字和姓氏出一个Telerik的radgrid控件。



我的问题在于试图在此拉动数据时获得用户ID一个不同的值。我试图重新工作的代码让我的结果。这里是被拉动所有数据的代码示例,用鲜明无法正常工作。

 公共静态的IQueryable GetActiveEmployees_Grid (串周期)
{
DataContext的数据=新的DataContext();
VAR员工=(从C在DataSystem_Records
,其中c.Period ==时期
排序依据c.DataSystem_Employees.LName
选择C).Distinct();

回报员工;
}



应用数据源到我的网后,将返回用户的4倍,人们例如每个记录这​​一时期。





有没有申请清晰到我的LINQ功能,使这项工作我就打算的方式方法?


解决方案

最简单的方法我发现这与对象使用GROUPBY然后选择第一次做。

 公共静态的IQueryable GetActiveEmployees_Grid(串周期)
{
DataContext的数据=新的DataContext();
VAR员工=(从C在DataSystem_Records
,其中c.Period ==时期
排序依据c.DataSystem_Employees.LName
选择C).GroupBy(G => g.DataSystem_Employees .AccID)。选择(X => x.FirstOrDefault());

回报员工;
}

这是未经测试,但一般的概念是存在的。



修改:我记得最初找到答案的地方就在这里。看看这个由某种性质分组的对象。
的LINQ在一个特定的属性

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.

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

解决方案

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 Distinct on a particular Property

这篇关于返回与LINQ鲜明的IQueryable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆