gpt4 book ai didi

c# - Entity Framework : OrderBy() numeric property when mapped column type is textual

转载 作者:行者123 更新时间:2023-11-30 23:18:02 25 4
gpt4 key购买 nike

 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 : OrderBy() numeric property when mapped column type is textual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41097309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com