[英]Complex LINQ to SQL query to return List<T>
我正在寫一個WP 8,它將顯示從WCF服務返回的列表。 我想從數據庫中選擇所有教師,然后從創建的列表中返回另一位教師,該教師將顯示5名教師的最大收入( maxInc
)最接近我的教師( MyMaxInc
)。 例如,如果MyMaxInc = 200
而我的用戶為225,用戶2為240,用戶3為210,則返回的列表將按以下順序顯示教師:用戶3,用戶,用戶2。 我的服務實現:
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
稍后將finalList
。 例如,當我在循環中創建列表時可以分配一些數字,並使用private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
方法。
更換
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)
結合使用Take(5)
最小差異排序的前5個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.