Skip to content

Latest commit

 

History

History
61 lines (56 loc) · 1.97 KB

Entity-SQL.md

File metadata and controls

61 lines (56 loc) · 1.97 KB

Ordering Nested Queries

In the Entity Framework, a nested expression can be placed anywhere in the query; the order of a nested query is not preserved.

-- The following query will order the results by the last name.

SELECT C1.FirstName, C1.LastName  
        FROM AdventureWorks.Contact as C1  
        ORDER BY C1.LastName  

-- In the following query, ordering of the nested query is ignored.

SELECT C2.FirstName, C2.LastName  
    FROM (SELECT C1.FirstName, C1.LastName  
        FROM AdventureWorks.Contact as C1  
        ORDER BY C1.LastName) as C2  

Multiple sort

var Result = Items.OrderBy(x => x.DateModified).ThenBy(x => x.DateCreated);

Assuming list is “Phones” and contains the following data

public class Phone
{
       public int ID { get; set; }
       public string Name { get; set; }
}
public class Phones : List
{
        public Phones()
        {
            Add(new Phone { ID = 1, Name = "Windows Phone 7" });
            Add(new Phone { ID = 5, Name = "iPhone" });
            Add(new Phone { ID = 2, Name = "Windows Phone 7" });
            Add(new Phone { ID = 3, Name = "Windows Mobile 6.1" });
            Add(new Phone { ID = 6, Name = "Android" });
            Add(new Phone { ID = 10, Name = "BlackBerry" });
        }
}
dataGridView1.DataSource = (from m in new Phones()
                                       orderby m.Name, m.ID
                                       select m).ToList();

The same we can do using lambda expression

dataGridView1.DataSource = new Phones().OrderByDescending(a => a.Name).ThenByDescending(a => a.ID).ToList();

Another way

qqq.OrderBy(x => new { x.Col1, x.Col2} )