175

How can I do this SQL query with Entity Framework?

SELECT DISTINCT NAME FROM TestAddresses
patrick
  • 16,091
  • 29
  • 100
  • 164

9 Answers9

344

Using lambda expression..

 var result = EFContext.TestAddresses.Select(m => m.Name).Distinct();

Another variation using where,

 var result = EFContext.TestAddresses
             .Where(a => a.age > 10)//if you have any condition
             .Select(m => m.name).Distinct();

Another variation using sql like syntax

 var result = (from recordset
              in EFContext.TestAddresses
              .where(a => a.city = 'NY')//if you have any condition
              .select new 
              {
                 recordset.name
              }).Distinct();
indiPy
  • 7,844
  • 3
  • 28
  • 39
  • 5
    Maybe a daft question, but does this return all addresses to the C# code layer and then filter them, or does this pass the appropriate query to the database server to return only the unique values? – D. A. Jun 20 '20 at 23:15
  • what would be the data type of result – Souradeep Banerjee-AIS Oct 14 '20 at 06:26
  • 3
    @D.A. EF will pass appropriate query to DB. https://stackoverflow.com/questions/37595253/entity-framework-6-query-with-distinct-filter – indiPy Nov 05 '20 at 16:09
60

Try this:

var results = (from ta in context.TestAddresses
               select ta.Name).Distinct();

This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    That way get better performance than grouping. Distinct : SQL Server Execution Times: CPU time = 0 ms, elapsed time = 50 ms. Grouping : SQL Server Execution Times: CPU time = 0 ms, elapsed time = 112 ms. – André Mendonça Jul 15 '15 at 22:02
32

The way that @alliswell showed is completely valid, and there's another way! :)

var result = EFContext.TestAddresses
    .GroupBy(ta => ta.Name)
    .Select(ta => ta.Key);

I hope it'll be useful to someone.

Kim Tranjan
  • 4,521
  • 3
  • 39
  • 38
30
DBContext.TestAddresses.Select(m => m.NAME).Distinct();

if you have multiple column do like this:

DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();

In this example no duplicate CategoryId and no CategoryName i hope this will help you

Muhammad Asad
  • 1,772
  • 16
  • 23
4

Entity-Framework Select Distinct Name:

Suppose if you are using Views in which you are using multiple tables and you want to apply distinct in that case first you have to store value in variable & then you can apply Distinct on that variable like this one....

public List<Item_Img_Sal_VIEW> GetItemDescription(int ItemNo) 
        {
            var Result= db.Item_Img_Sal_VIEW.Where(p => p.ItemID == ItemNo).ToList();
            return Result.Distinct().ToList();
        }

Or you can try this Simple Example

Public Function GetUniqueLocation() As List(Of Integer)
          Return db.LoginUsers.Select(Function(p) p.LocID).Distinct().ToList()
End Function
Abdul Khaliq
  • 2,139
  • 4
  • 27
  • 31
  • Hi, when I do this on a table, I get an error -> **cannot convert string to IEnumreable..** can you show me how to get a list so I can populate a drop down list, with distinct values from a table column containing NVARCHAR in EF DB. – aggie Oct 22 '14 at 00:37
3

use Select().Distinct()

for example

DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();
Hossein Hajizadeh
  • 1,357
  • 19
  • 10
2

In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT error, the best should be

var results = (
    from ta in DBContext.TestAddresses
    select ta.Name
)
.Distinct()
.OrderBy( x => 1);
overcomer
  • 2,244
  • 3
  • 26
  • 39
1

Entity-Framework Select Distinct Name:

Suppose if you are want every first data of particular column of each group ;

 var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();

            foreach (var item in data)
            {
                var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();

               //Eg.
                {
                       ListBox1.Items.Add(data2.ColumnName);                    
                }

            }
-2

.Distinct() use default equality comparer for table, which might not be the one we want, something this could give us not the right answer, so we can use DistinctBy which uses a specific key.

DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).DistinctBy(m=>m.NAME);

if you want with multiple columns just use .DistinctBy(m=> new{m.NAME, m.ID})

  • I forgive you :), obviously if they are strings and that is the default comparator it is irrelevant, but what we want to compare is not always the default comparator. Furthermore, nobody had mentioned in this question DistinctBy before. Glad to help – Sphero Venezuela Mar 17 '23 at 13:07
  • 1
    `Distinct` over strings doesn't require an explicit comparison key. Also please note that `DistinctBy` isn't currently supported by Entity Framework. – Gert Arnold Mar 17 '23 at 14:05
  • I kindly invite you to review EF, it has evolved in the last 5 years. If you consider that please just tag my answer – Sphero Venezuela Mar 17 '23 at 14:20
  • I kindly invite you to test your code in EFC 7.0, the current stable EF version. – Gert Arnold Mar 17 '23 at 14:45
  • Exactly, hundreds LOC using it since 2022 https://canro91.github.io/2022/06/27/NET6LinqMethods/ – Sphero Venezuela Mar 17 '23 at 14:52
  • LINQ to objects != LINQ to entities. Test it. – Gert Arnold Mar 17 '23 at 14:56