我有这段代码:
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>();
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用try catch来确保转换不会引发错误,但我想知道如何在linq语句中使用TryParse来完成这项工作.
谢谢.
TheListOfIDs = TheString.Split(',')
.Select(s =>
{
int i;
return Int32.TryParse(s, out i) ? i : -1;
}).ToList();
Run Code Online (Sandbox Code Playgroud)
这将返回-1任何失败的转换.
TheListOfLeadIDs = (from string s in TheString.Split(',')
let value = 0
where int.TryParse(s, out value)
select value).ToList<int>();
Run Code Online (Sandbox Code Playgroud)