Entity Framework select distinct name

前端 未结 8 1898
小蘑菇
小蘑菇 2020-12-12 14:18

How can I do this SQL query with Entity Framework?

SELECT DISTINCT NAME FROM TestAddresses
相关标签:
8条回答
  • 2020-12-12 14:33

    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.

    0 讨论(0)
  • 2020-12-12 14:35

    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);                    
                    }
    
                }
    
    0 讨论(0)
  • 2020-12-12 14:40

    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>.

    0 讨论(0)
  • 2020-12-12 14:41

    Using lambda expression..

     var result = EFContext.TestAddresses.Select(m => m.Name).Distinct();
    
    0 讨论(0)
  • 2020-12-12 14:42

    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
    
    0 讨论(0)
  • 2020-12-12 14:45
    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

    0 讨论(0)
提交回复
热议问题