return JsonConvert.SerializeObject(new Entities()
.Student_Master
.Where(k => k.Student_Location == Location && k.Student_Course == Program)
.OrderBy(i => i.Student_Batch)
.Select(i => i.Student_Batch)
.Distinct()
.ToList());
输出:
[23,24,28,25,30,26,27,29]
需要输出
[23,24,25,26,27,28,29,30]
我尝试使用
OrderBy(i => i.Student_Batch)
,但在数据库Student_Batch
中数据类型为string
,因此无法正确排序我试着喜欢
var data=new Entities().Student_Master.Where(k => k.Student_Location == Location && k.Student_Course == Program).OrderBy(i => i.Student_Batch).Select(i => i.Student_Batch).Distinct().ToList();
foreach(var obj in data)
{
//converted string to int then store in array
}
有什么简单的方法吗?
最佳答案
好的,因为问题在于排序。您的选择很少,我将显示其中2个。首先是可以使用Array.Sort()
这是很常见的:
string[] values = new Entities()
.Student_Master
.Where(k => k.Student_Location == Location && k.Student_Course == Program).Select(i => i.Student_Batch)
.Distinct().ToArray();
Array.Sort(values); // all you need.
第二种常见方法是创建自定义比较器,并在
OrderBy
中使用它:public class MeComparer : IComparer<string> {
public int Compare(string stringA, string stringB) {
// your compare logic goes here...
// eg. return int.Parse(stringA) - int.Parse(stringB)
}
}
// and use it like
return JsonConvert.SerializeObject(new Entities()
.Student_Master
.Where(k => k.Student_Location == Location && k.Student_Course == Program)
.Select(i => i.Student_Batch)
.Distinct()
.ToList()
.OrderBy(i => i.Student_Batch, new MeComparer()) // <-- HERE
);
关于c# - Entity Framework :映射的列类型为文本时的Order By()数字属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41097309/