如何从LINQ获取实体的唯一值?

时间:2016-01-01 05:57:01

标签: c# asp.net entity-framework linq

我有 using (ProjectEntities myEntities = new ProjectEntities ()) { var q = (from c in myEntities.Customers orderby c.Name select c.Name); DropDownList1.DataSource = q.ToList(); DropDownList1.DataBind(); } 从此查询中获取数据:

ng-model

如何获得唯一的名称?

2 个答案:

答案 0 :(得分:3)

只需添加 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();

答案 1 :(得分:1)

您可以对从当前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();