从带有where子句的数据表中选择

时间:2015-03-16 11:14:31

标签: c# asp.net select datatable

我正在尝试从数据表中选择几行。我正在选择两个列,如何在下面的语句中使用where子句?

cars = new Head
{
    heading = (string)dr["head"],
    subHeads = dt.Select(r => new SubHead
    {                               // how to use a where clause here?
        subHeading = (string)r["subhead"],
        cars = dt.Select(r2 => new Cars
        {                           // how to use a where clause here?
            name = (string)r2["name"],
            quantity = (string)r2["qty"],
        }).ToList()
     }).ToList()
 };

2 个答案:

答案 0 :(得分:1)

你可以用,

dt.where(e => {check something}).Select({select code here})

在这两个地方都这样做。希望这会有所帮助。

答案 1 :(得分:1)

您需要在选择之前调用Where。例如:

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

var contacts = ds.Tables["Contact"].AsEnumerable();
var orders = ds.Tables["SalesOrderHeader"].AsEnumerable();

var query =
    contacts.SelectMany(
        contact => orders.Where(order =>
            (contact.Field<Int32>("ContactID") == order.Field<Int32>("ContactID"))
                && order.Field<decimal>("TotalDue") < 500.00M)
            .Select(order => new
            {
                ContactID = contact.Field<int>("ContactID"),
                LastName = contact.Field<string>("LastName"),
                FirstName = contact.Field<string>("FirstName"),
                OrderID = order.Field<int>("SalesOrderID"),
                Total = order.Field<decimal>("TotalDue")
            }));

foreach (var smallOrder in query)
{
    Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Total Due: ${4} ",
        smallOrder.ContactID, smallOrder.LastName, smallOrder.FirstName,
        smallOrder.OrderID, smallOrder.Total);
}

取自here