如何通过LINQ生成等效查询c#

时间:2015-07-22 15:08:49

标签: c# linq

这是我的内联sql查询。我希望由LINQ生成相同的等效查询。

var lowerPageBoundary = 0;
var tableName = "Orders";
var columnToSortBy = "OrderID";
var sortColumn = "OrderID";
var rowsPerPage = 16;
var CommaSeparatedListOfColumnNames = "OrderID,CustomerID,EmployeeID ";

var SQL = "Select Top " + rowsPerPage + " " +
    CommaSeparatedListOfColumnNames + " From " + tableName +
    " WHERE " + columnToSortBy + " NOT IN (SELECT TOP " +
    lowerPageBoundary + " " + columnToSortBy + " From " +
    tableName + " Order By " + sortColumn +
    ") Order By " + sortColumn;

到目前为止这是我的LINQ查询。只是告诉我如何自定义它以获得像上面的内联SQL查询一样的输出。

    XDocument document = XDocument.Load(xmlFilePath);
    var query = from r in document.Descendants("orders")
        select new
        {
            OrderID = r.Element("OrderID").Value,
            CustomerID = r.Element("CustomerID").Value,
            EmployeeID = r.Element("EmployeeID").Value
        };
    query = query.OrderBy(sortColumn + " " + OrderDirection);

如何使它像上面的sql查询一样嵌套并添加像上面的sql一样的分页概念。

1 个答案:

答案 0 :(得分:1)

如果您发布原始SQL查询会更容易,但这是我的看法:

document
.Where(x=> !documents.OrderBy(p=> p.OrderID)
                     .Take(sortColumn)
                     .Contains(x))
.Select(p=> new {...})
.OrderBy(...).Take(...)

编辑:

或者更好:

var hashSet = new HashSet<Whatever>(
                     documents.OrderBy(p=> p.OrderID)
                              .Take(sortColumn));
document
.Where(x=> !hashSet.Contains(x))
.Select(p=> new {...})
.OrderBy(...).Take(...)