C# 从 DataRow [] 集合中选择一个 DataRow

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17567830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:51:18  来源:igfitidea点击:

Select a DataRow from a DataRow [] collection

c#asp.net

提问by Sora

My code :

我的代码:

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

A row contains TEMPLATE_ID,MIN_AMOUNT,MAX_AMOUNTand DISCOUNT

一行包含TEMPLATE_IDMIN_AMOUNTMAX_AMOUNTDISCOUNT

Now I want to select a row where a given amount is between MIN_AMOUNTand MAX_AMOUNT

现在我想选择给定金额介于MIN_AMOUNT和之间的行MAX_AMOUNT

I tried to do this :

我试图这样做:

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

but this didn't work.

但这没有用。

采纳答案by Tim Schmelter

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 table = rows.CopyToDataTable();

Note that CopyToDataTablethrows an exception if there are no rows since it must derive the columns from the rows. So you have to check it before. You could use:

请注意,CopyToDataTable如果没有行,则抛出异常,因为它必须从行派生列。所以你必须先检查它。你可以使用:

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.Selecton a DataRow[]

顺便说一句,你的问题是你DataTable.SelectDataRow[]

回答by gzaxx

You have to select rows again from your DataTableif you want to use Select()method

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

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

回答by sangram parmar

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);