【问题标题】:Sorting SQL list by int按 int 对 SQL 列表进行排序
【发布时间】:2015-08-19 10:23:46
【问题描述】:

我对 MVC 和实体框架还很陌生,我希望有人能够帮助我。

我有一个 SQL 数据库,其中有一列包含整数。我想将这些值取出并放入 html.dropdownlistfor

我最初是想这样做的:

List<SelectListItem> List = dbAccess.KeywordCorrelationData.Select(
temp => new {
    Value = temp.DefaultDestroyPeriod.ToString(), 
    Text = temp.DefaultDestroyPeriod.ToString()
}).OrderBy(temp => temp.Value).Distinct().ToList();

但是,这仅按文本值而非数值排序。

我已经找到了一个解决方案,但它的时间要长得多:

List<SelectListItem> List= new List<SelectListItem>();

List<int> tempIntList = dbAccess.KeywordCorrelationData.Select(temp => temp.DefaultDestroyPeriod).Distinct().ToList(); 

tempIntList.Sort();

foreach (int tempInt in tempIntList)
{
    int wholeYears = (int)Math.Round((double)tempInt / 365, 0);
    SelectListItem newItem = new SelectListItem()
    {
        Value = tempInt.ToString(),
        Text = tempInt.ToString() + " days (approx. " + wholeYears.ToString() + (wholeYears == 1 ? " year)" : " years)")
    };

    List.Add(newItem);
}

return List;

我想知道是否有比这更简单的方法?我在这里用谷歌搜索和搜索过,但找不到类似的东西。

谢谢

【问题讨论】:

  • DefaultDestroyPeriod的数据类型是什么?

标签: c# sql model-view-controller entity-framework-5


【解决方案1】:

假设DefaultDestroyPeriod 已经是数字类型,只需在执行Select 之前应用排序:

List<SelectListItem> List = dbAccess.KeywordCorrelationData
    .OrderBy(kcd => kcd.DefaultDestroyPeriod)
    .Select(kcd => new
    {
        Value = kcd.DefaultDestroyPeriod.ToString(), 
        Text = kcd.DefaultDestroyPeriod.ToString()
    }).Distinct().ToList();

【讨论】:

  • 我刚试过这个,它提取了数据,但没有按正确的顺序排序。并回答您的其他评论 DefaultDestroyPeriod 是一个 int
猜你喜欢
  • 2022-11-17
  • 2022-01-18
  • 2022-01-14
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多