user4451265
user4451265

Reputation:

How to get unique values from LINQ to Entities?

I have a DropDownList which gets its data from this query:

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

How to get just the unique names?

Upvotes: 1

Views: 84

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222582

Just add Distinct

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

or on the query itself,

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

Upvotes: 3

Shyju
Shyju

Reputation: 218732

You can call Distinct() method on the result you get from your current linq expression.

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

or

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

Upvotes: 1

Related Questions