复杂的LINQ到SQL查询返回List

本文关键字:List 返回 查询 LINQ SQL 复杂 | 更新日期: 2023-09-27 18:15:18

我正在写一个WP 8,它将显示从WCF服务返回的列表。我想从数据库中选择所有教师,然后从创建的列表中返回另一个列表,该列表将显示5位最大收入(maxInc)最接近我的(MyMaxInc)的教师。例如,如果MyMaxInc = 200和我的user为225,user2为240,user3为210,返回的列表将按照以下顺序显示教师:user3, user, user2。我的服务实现:

public IEnumerable<mTeachers> GetStuffList(int MyMaxInc, int MyMinInc)
    {
        List<mTeachers> stuffList = new List<mTeachers>();
        DataClasses1DataContext data = new DataClasses1DataContext();
        int inc = 0;
        List<mTeachers> finalList = new List<mTeachers>();
            foreach (var d in data.Stuffs)
            {
                if (d.stuffJob == "teacher") 
                {                   
                    stuffList.Add(new mTeachers(d.stuffName, (int)d.maxInc, (int)d.minInc, "teacher", inc)); inc++;       
                }
            }
            if (inc > 0) 
            {
                foreach (mTeachers element in stuffList)             
                    if () {/*didn't finish this bit because 
                         don't know how to create second list*/ } 
                return finalList;
            }
            else return null;           
    }
服务接口:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    IEnumerable<mTeachers> GetStuffList(int MyMaxInc, int MyMinInc);
    }
[DataContract]
public class mTeachers
{
    [DataMember]
    public string Name;
    [DataMember]
    public int maxInc;
    [DataMember]
    public int minInc;
    [DataMember]
    public string Job;
    [DataMember]
    public int Number;
    public mTeachers(string Name, int maxInc, int minInc, string Job, int Number)
    {
        this.maxInc = maxInc;
        this.minInc = minInc;
        this.Name = Name;
        this.Job = Job;
        this.Number = Number;
    }
}

我还创建了mTeachers类的Number成员finalList组稍后。例如,当我在循环中创建列表并使用private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)方法将其分组时,我可以分配一些数字。

复杂的LINQ到SQL查询返回List<T>

Replace

           foreach (mTeachers element in stuffList)             
                if () {/*didn't finish this bit because 
                     don't know how to create second list*/ } 

finalList.AddRange(
    stuffList.OrderBy(x => Math.Abs(x.maxInc - MyMaxInc)).Take(5));

Math.Abs(...)将负差值转换为正差值,以便能够同时比较较小和较大的值。

OrderBy结合Take(5)取前5个元素,按差值最小排序。