代码之家  ›  专栏  ›  技术社区  ›  nightingale2k1

实体框架核心2.1如何使用OrderBy()和Distinct()

  •  -1
  • nightingale2k1  · 技术社区  · 6 年前

    我想从我的表中选择distinct来获得年份列表 所以我写了代码:

    return await _context.SdrSettingHistory
                    .Where( x => x.StartDate != null)
                    .OrderBy(x => x.StartDate)
                    .Select(x => x.StartDate.Value.Year)
                    .Distinct()
                    .ToListAsync();
    

    我该怎么点年货?

    我尝试在Distinct()之后移动OrderBy,但它产生错误:

    error CS1061: 'int' does not contain a definition for 'StartDate' and no accessible extension method 'StartDate' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
    

    注:

    1 回复  |  直到 6 年前
        1
  •  3
  •   Douglas    6 年前

    这个 Select Distinct 不能保证运算符在其他数据提供程序(如SQL Server)上保持顺序。你得动一下你的手 OrderBy 接线员在后面。因为你的计划价值 选择 int ,您可以直接订购:

    return await _context.SdrSettingHistory
        .Where(x => x.StartDate != null)
        .Select(x => x.StartDate.Value.Year)
        .Distinct()
        .OrderBy(x => x)
        .ToListAsync();