C# 在 LINQ 中将字符串转换为 Int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16820855/
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
Convert String To Int in LINQ
提问by kformeck
I have a LINQ query that queries a DataTable. In the DataTable, the field is a string and I need to compare that to an integer, basically:
我有一个查询数据表的 LINQ 查询。在 DataTable 中,该字段是一个字符串,我需要将它与一个整数进行比较,基本上:
if ((electrical >= 100 && electrical <= 135) || electrical == 19)
{
// The device passes
}
the problem is, I am trying to do this in LINQ like this:
问题是,我试图在 LINQ 中这样做:
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where (Int32.Parse(row.Field<String>("electrical")) >= 100 &&
Int32.Parse(row.Field<String>("electrical")) <= 135) &&
Int32.Parse(row.Field<String>("electrical")) != 19 &&
row.Field<String>("print") == printName
select row;
I keep getting the exception:
我不断收到异常:
Input string was not in a correct format
输入字符串的格式不正确
The main problem occurs when electrical == ""
主要问题出现在电气==""
采纳答案by kformeck
I could not get anything to work, so I re-did the whole method:
我什么都做不了,所以我重新做了整个方法:
public bool GetElectricalStatus(string printName)
{
List<object> eGoodList = new List<object>();
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where row.Field<String>("print") == printName
select row.Field<String>("electrical");
foreach (var eCode in eGoodCountQuery)
{
if (!string.IsNullOrEmpty(eCode.ToString()))
{
int? eCodeInt = Convert.ToInt32(eCode);
if (eCodeInt != null &&
(eCodeInt >= 100 && eCodeInt <= 135) || eCodeInt == 19)
{
eGoodList.Add(eCode);
}
}
}
if (eGoodList.Count() > 0)
{
return false;
}
else
{
return true;
}
}
The main problem occurs when electrical == ""
主要问题出现在电气==""
回答by Joanna Derks
I would check if the data in the column does not contain leading/trailing whitespaces - i.e. "15 "rather than "15"and if it does (or might do) trim it before trying to convert:
我会检查列中的数据是否不包含前导/尾随空格 - 即"15 "而不是"15"在尝试转换之前它是否(或可能)修剪它:
Int32.Parse(row.Field<String>("electrical").Trim())
Int32.Parse(row.Field<String>("electrical").Trim())
BTW: not related to the error but I'd use letstatement to introduce a local variable and do the conversion once:
顺便说一句:与错误无关,但我会使用let语句来引入局部变量并进行一次转换:
let x = Int32.Parse(row.Field<String>("electrical").Trim())
where x >= 100...
回答by Sean H
Why not make a function that does your evaluation, and call it in your Linq query. Put logic in to check the validity of the data contained within (so if you can't parse the data, it should return false)...
为什么不创建一个进行评估的函数,并在您的 Linq 查询中调用它。放入逻辑以检查其中包含的数据的有效性(因此,如果您无法解析数据,则应返回false)...
The function:
功能:
bool IsInRange(string text, int lower, int upper, params int[] diqualifiers)
{
int value = int.MinValue;
if (!int.TryParse(text, out value)) {
return false;
}
if (!(value >= lower && value <= upper)) {
return false;
}
if (disqualifiers != null && disqualifiers.Any(d => d == value)) {
return false;
}
return true;
}
The Linq query...
Linq 查询...
var eGoodCountQuery =
from row in singulationOne.Table.AsEnumerable()
where
IsInRange(row.Field<String>("electrical"), 100, 135, 19)
&& row.Field<String>("print") == printName
select row;
回答by Jeff Mercado
Unfortunately, the framework doesn't provide a nice clean way to handle parsing scenarios where it fails. Of what's provided, they only throw exceptions or use outparameters, both of which does not work well with linq queries. If any one value you're parsing fails, the entire query fails and you just can't really use outparameters. You need to provide a method to handle the parsing without that does not throw and does not require using outparameters.
不幸的是,该框架没有提供一种很好的干净的方法来处理它失败的解析场景。在所提供的内容中,它们只抛出异常或使用out参数,这两者都不适用于 linq 查询。如果您解析的任何一个值失败,整个查询就会失败,您就不能真正使用out参数。您需要提供一种方法来处理解析,而无需抛出且不需要使用out参数。
You can handle this in many ways. Implement it where upon failure, you return some default sentinel value.
您可以通过多种方式处理此问题。在失败时实现它,你返回一些默认的哨兵值。
public static int ParseInt32(string str, int defaultValue = 0)
{
int result;
return Int32.TryParse(str, out result) ? result : defaultValue;
}
Or what I would recommend, return a nullable value (nullindicating it failed).
或者我会推荐什么,返回一个可为空的值(null表示它失败)。
public static int? ParseInt32(string str)
{
int result;
return Int32.TryParse(str, out result) ? result : null;
}
This simplifies your query dramatically while still leaving it readable.
这极大地简化了您的查询,同时仍保持其可读性。
public bool GetElectricalStatus(string printName)
{
var query =
from row in singulationOne.Table.AsEnumerable()
where row.Field<string>("print") == printName
// using the nullable implementation
let electrical = ParseInt32(row.Field<string>("electrical"))
where electrical != null
where electrical == 19 || electrical >= 100 && electrical <= 135
select row;
return !query.Any();
}
p.s., your use of the Convert.ToInt32()method is incorrect. It is the same as calling Int32.Parse()and does notreturn a nullable, it will throw on failure.
ps,你使用的Convert.ToInt32()方法不对。它与调用相同Int32.Parse()并且不返回可空值,它会在失败时抛出。

