7

我有这段代码:

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 使其工作。

谢谢。

4

4 回答 4

8
TheListOfIDs = TheString.Split(',')
                        .Select(s => 
                        {
                            int i;
                            return Int32.TryParse(s, out i) ? i : -1;
                        }).ToList();

这将为-1任何失败的转换返回一个。

于 2012-04-21T12:29:51.553 回答
7
TheListOfLeadIDs = (from string s in TheString.Split(',')
                    let value = 0
                    where int.TryParse(s, out value)
                    select value).ToList<int>();
于 2012-04-21T12:28:40.677 回答
3

你可以这样做:

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();
于 2012-04-21T12:50:00.423 回答
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>();

这意味着您只会获得成功解析的价值......

于 2012-04-21T12:41:59.297 回答