-6

LINQ-我使用 order by 子句按升序排序以获取数据库中可用的所有状态,但它不起作用。这是代码:

 public List<State> GetAllStates()
    {
        List<State> p;
        p = (from a in _db.ProductImageMaps
             where a.State != "" && a.State != null
             select new State
             {
                 Name = a.State
             }).OrderBy(a=>a.Name).Distinct().ToList();
        return p;

    }
4

1 回答 1

2

按设计Disitnct返回源中唯一项的无序序列。

因此,当您在 order by 子句之后调用 Distinct 时,您将失去您所追求的序列。其次,在 Distinct 之后调用 OrderBy 对我来说更有意义,因为只订购 Distinct Records 会更有效。

像这样做

public List<State> GetAllStates()
    {
        List<State> p;
        p = (from a in _db.ProductImageMaps
             where a.State != "" && a.State != null
             select new State
             {
                 Name = a.State
             }).Distinct().OrderBy(a=>a.Name).ToList();
        return p;

    }
于 2013-10-21T11:17:47.510 回答