我有这段代码:
TheString = "443,432,546,4547,4445,2,132"; //actually, about 1000 entries
List<int> TheListOfIDs = new List<int>();
TheListOfLeadIDs = from string s in TheString.Split(',')
select Convert.ToInt32(s)).ToList<int>();
我知道我可以使用try catch来确保转换不会引发错误,但我想知道如何在linq语句中使用TryParse来完成这项工作。
感谢。
答案 0 :(得分:7)
TheListOfLeadIDs = (from string s in TheString.Split(',')
let value = 0
where int.TryParse(s, out value)
select value).ToList<int>();
答案 1 :(得分:6)
TheListOfIDs = TheString.Split(',')
.Select(s =>
{
int i;
return Int32.TryParse(s, out i) ? i : -1;
}).ToList();
对于任何失败的转化,这将返回-1
。
答案 2 :(得分:2)
你可以这样做:
string TheString = "443,432,546,4547,4445,2,132"; //actually, about 1000 entries
int temp=0;
var TheListOfIDs= TheString
.Split(',')
.Where (ts =>int.TryParse(ts,out temp))
.Select (ts =>temp )
.ToList();
答案 3 :(得分:0)
警告:未尝试过。
string[] myString = TheString.Split(',');
int leadId;
var theListOfLeadIds = (from myString in myString where int.TryParse(myString, out leadId) select int.Parse(myString)).ToList<int>();
意味着您只能成功解析值...