[英]Complex LINQ to SQL query to return List<T>
I'm writing a WP 8 that will show list returned from the WCF service. 我正在写一个WP 8,它将显示从WCF服务返回的列表。 I want to select all teachers from the database and then from the created list return another one that will show 5 teachers whose maximum income (
maxInc
) is closest to mine ( MyMaxInc
). 我想从数据库中选择所有教师,然后从创建的列表中返回另一位教师,该教师将显示5名教师的最大收入(
maxInc
)最接近我的教师( MyMaxInc
)。 For example if MyMaxInc = 200
and I have user with 225, user2 with 240 and user3 with 210 the returned list will show teachers in the following order: user3, user, user2. 例如,如果
MyMaxInc = 200
而我的用户为225,用户2为240,用户3为210,则返回的列表将按以下顺序显示教师:用户3,用户,用户2。 My service implementation: 我的服务实现:
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;
}
Service interface: 服务界面:
[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;
}
}
Also I created Number
member of mTeachers
class to group finalList
later. 我还创建了
mTeachers
类的Number
成员, finalList
稍后将finalList
。 For example I can assign some number when I'm creating a list in the loop and the group it with private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
method. 例如,当我在循环中创建列表时可以分配一些数字,并使用
private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
方法。
Replace 更换
foreach (mTeachers element in stuffList)
if () {/*didn't finish this bit because
don't know how to create second list*/ }
with 同
finalList.AddRange(
stuffList.OrderBy(x => Math.Abs(x.maxInc - MyMaxInc)).Take(5));
Math.Abs(...)
converts negative differences to positive to be able to compare smaller and larger values at the same time. Math.Abs(...)
将负差转换为正,以便能够同时比较较小和较大的值。
OrderBy
combined with Take(5)
takes the 5 first elements sorted by the smallest difference. OrderBy
与Take(5)
结合使用Take(5)
最小差异排序的前5个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.