简体   繁体   English

从DataRow []集合中选择DataRow

[英]Select a DataRow from a DataRow [] collection

My code : 我的代码:

DataRow[] row = ByTotalTemplate.Select("TEMPLATE_ID=" + DisTemplateID);

A row contains TEMPLATE_ID , MIN_AMOUNT , MAX_AMOUNT and DISCOUNT 一行包含TEMPLATE_IDMIN_AMOUNTMAX_AMOUNTDISCOUNT

Now I want to select a row where a given amount is between MIN_AMOUNT and MAX_AMOUNT 现在我想选择给定金额介于MIN_AMOUNTMAX_AMOUNT之间的行

I tried to do this : 我试着这样做:

DataRow amountRow = row.Select("MIN_AMOUNT<" + quantity + " AND MAX_AMOUNT>" + quantity);

but this didn't work. 但这没用。

Instead of fiddling around with the expression syntax i would use Linq: 而不是摆弄表达式语法我会使用Linq:

IEnumerable<DataRow> rows = ByTotalTemplate.AsEnumerable()
           .Where(r => r.Field<int>("TEMPLATE_ID") == DisTemplateID
                    && r.Field<int>("MIN_AMOUNT") < quantity
                    && r.Field<int>("MAX_AMOUNT") > quantity);

If you want a new DataTable with the filtered result: 如果您想要一个带有过滤结果的新DataTable:

DataTable table = rows.CopyToDataTable();

Note that CopyToDataTable throws an exception if there are no rows since it must derive the columns from the rows. 请注意,如果没有行, CopyToDataTable会抛出异常,因为它必须从行派生列。 So you have to check it before. 所以你必须先检查一下。 You could use: 你可以使用:

DataTable table = ByTotalTemplate.Clone();
if(rows.Any())
    table = rows.CopyToDataTable();

If you want an array instead: 如果你想要一个数组:

DataRow[] rowArray = rows.ToArray();

If you just want the first row: 如果你只想要第一行:

DataRow row = rows.FirstOrDefault(); // can be null if there is no matching row

Btw, your problem was that you used DataTable.Select on a DataRow[] 顺便说一下,你的问题是你在DataRow[]上使用DataTable.Select

如果要使用Select()方法,则必须再次从DataTable选择行

DataRow[] rowsBetween = ByTotalTemplate.Select("TEMPLATE_ID = " + DisTemplateID + " AND MIN_AMOUNT < " + qunatity + " AND MAX_AMOUNT > " + qunatity);

try this 试试这个

        DataRow[] row = ByTotalTemplate.Select("TEMPLATE_ID=" + DisTemplateID);
        //
        //some use of **row** here 
        //than after select record from **row**
        DataRow[] amountRow = row.CopyToDataTable().Select("MIN_AMOUNT < " + qunatity + " AND MAX_AMOUNT > " + qunatity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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