如何从LINQ到实体获取唯一值

本文关键字:获取 唯一 实体 LINQ | 更新日期: 2023-09-27 18:28:34

我有一个DropDownList,它从这个查询中获取数据:

    using (ProjectEntities myEntities = new ProjectEntities ())
                {
                    var q = (from c in myEntities.Customers orderby c.Name select c.Name);
                    DropDownList1.DataSource = q.ToList();
                    DropDownList1.DataBind();
}

如何只获取唯一的名称?

如何从LINQ到实体获取唯一值

只需添加Distinct

 var q = (from c in myEntities.Customers orderby c.Name select c.Name);
 DropDownList1.DataSource = q.ToList().Distinct();

或者查询本身,

 var q = (from c in myEntities.Customers orderby c.Name select c.Name).Distinct();

您可以对从当前linq表达式获得的结果调用Distinct()方法。

var q = (from c in myEntities.Customers orderby c.Name select c.Name).Distinct();

var q = myEntities.Customers.OrderBy(s=>s.Name).Select(f=>f.Name).Distinct();