简体   繁体   中英

Join and order in LINQ C#

I have been given the following skeleton code:

var test = SqlCompact(
"OrderID", "ASC", 5, 2,
 out count, out sortCriteria, out sql);

This calls the SqlCompact method which performs joins of tables orders, employees and customers & then orders by the inputs eg "ASC" and "Column Name".

I have got the join query working but not sure how to order the results according to the input. This is my code for SqlCompact Method:

public List<MyJoin> SqlCompact(
    string sort, string sortDir, int rowsPerPage, int page, 
    out int count, out string sortCriteria, out string sql) {    

var cec = new SqlCeConnection(
    string.Format(@"Data Source={0}\Northwind.sdf", Path));
var nwd = new DataContext(cec);

nwd.Log = new StringWriter();
var orders = nwd.GetTable<Order>();
var employees = nwd.GetTable<Employee>(); //
var customers = nwd.GetTable<Customer>(); //

count = orders.Count();
sortCriteria = "";

 var q = (from od in orders
        join em in employees on od.EmployeeID equals em.EmployeeID
        join ct in customers on od.CustomerID equals ct.CustomerID
        //orderby em.EmployeeID
        select new
        {
            od.OrderID,
            od.ShipCountry,
            ct.CompanyName,
            ct.ContactName,
            FullName = em.FirstName + ' '+ em.LastName, 
        }).ToList();

q.Dump();

sortCriteria: a string composed from sort and sortDir – in the format directly usable by Dynamic LINQ, eg

OrderID ASC 
ContactName DESC, OrderID DESC

This is what you want to do: if (sort == "OrderId") { q = q.OrderBy(x => x.OrderId); }

Passing in the the column name as a string is not a great way to do it though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM