C# DataTable.Select 字符串函数在 where 子句中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19289597/
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
DataTable.Select string function in where clause
提问by Conrad Lotz
I'm having problems with a DataTable.Select()
where the matching values might contain leading spaces and need to be trimmed correctly to return the correct amount of records.
我遇到DataTable.Select()
了匹配值可能包含前导空格的问题,需要正确修剪以返回正确数量的记录。
Currently my code is returning less records as the matching fails because of unwanted characters.
目前,由于不需要的字符,匹配失败,我的代码返回的记录较少。
How do you handle DataTable.Select as the example SQL below suggests?
你如何处理 DataTable.Select 作为下面的示例 SQL 建议?
SELECT * FROM Table WHERE LTRIM(FullName) = ' Joe Smith'
I' tried
我试过
dataTable.Select("LTRIM(FullName) = ' Joe Smith'");
but it failed.
但它失败了。
Any ideas?
有任何想法吗?
采纳答案by Tim Schmelter
I would suggest to use Linq-To-DataSet
instead, it makes it a lot clearer and easier to maintain:
我建议Linq-To-DataSet
改用它,它使它更清晰,更易于维护:
var rows = from row in dataTable.AsEnumerable()
where row.Field<string>("FullName").Trim() == "Joe Smith"
select row;
If you want to use LTRIM
instead, you just have to replace Trim
with TrimStart
.
如果你想LTRIM
改用,你只需要替换Trim
为TrimStart
.
if you want an array or list, use ToArray
or ToList
, e.g.
如果你想要一个数组或列表,使用ToArray
or ToList
,例如
DataRow[] rowsArray = rows.ToArray();
or a DataTable
或数据表
dataTable = rows.CopyToDataTable();
Edit: if you insist on using DataTable.Select
or you can't use linq, this should work(LTRIM
is not supported):
编辑:如果您坚持使用DataTable.Select
或不能使用 linq,这应该可以工作(LTRIM
不支持):
rowsArray = dataTable.Select("TRIM(FullName) = 'Joe Smith'");
回答by codingbadger
Give this a try:
试试这个:
string searchTerm = " Joe Smith";
string expression = String.Format("TRIM(FullName) = '{0}'", searchTerm.Trim());
dataTable.Select(expression);
回答by Satyaniti Singh
DataTable excelData = objGetExcelData.DataExcel(objEntities.StrFilePath, ConfigSettings.GetAppConfigValue("select * from sheet1"));
StringBuilder strInput = new StringBuilder();
DataView view = new DataView(excelData);
DataTable distinctValues = view.ToTable(true, "GROUP_NAME");
if (distinctValues.Rows.Count > 0)
{
for (int i = 0; i < distinctValues.Rows.Count; i++)
{
strGroupName = Convert.ToString(distinctValues.Rows[i]["GROUP_NAME"]);
foreach (DataRow item in excelData.Select("GROUP_NAME = '" + strGroupName + "'"))
{
strInput.Append(Convert.ToString(item[0]));
strInput.Append("~");
strInput.Append(Convert.ToString(item[1]));
strInput.Append(",");
strDasID = Convert.ToString(item[0]);
}
}
}