2013-01-13 37 views
2

我使用一個轉換到List<string>轉換爲List<UInt32>轉換出現FormatException處理

它確實很好,但是當數組元素之一不是可轉換,ToUint32扔FormatException

我想通知用戶有關失敗的元素。

try 
{ 
    List<UInt32> MyList = SomeStringList.ConvertAll(new Converter<string, UInt32>(element => Convert.ToUInt32(element))); 
} 

catch (FormatException ex) 
{ 
     //Want to display some message here regarding element. 
} 

我正在捕捉FormatException,但無法找到它是否包含字符串名稱。

回答

3

您可以捕捉異常拉姆達內:

List<UInt32> MyList = SomeStringList.ConvertAll(new Converter<string, UInt32>(element => 
{ 
    try 
    { 
     return Convert.ToUInt32(element); 
    } 
    catch (FormatException ex) 
    { 
     // here you have access to element 
     return default(uint); 
    } 
})); 
3

你可以使用TryParse方法:

var myList = someStringList.ConvertAll(element => 
{ 
    uint result; 
    if (!uint.TryParse(element, out result)) 
    { 
     throw new FormatException(string.Format("Unable to parse the value {0} to an UInt32", element)); 
    } 
    return result; 
}); 
0

這裏是什麼,我會在本次比賽使用:

List<String> input = new List<String> { "1", "2", "three", "4", "-2" }; 

List<UInt32?> converted = input.ConvertAll(s => 
{ 
    UInt32? result; 

    try 
    { 
     result = UInt32.Parse(s); 
    } 
    catch 
    { 
     result = null; 
     Console.WriteLine("Attempted conversion of '{0}' failed.", s); 
    } 

    return result; 
}); 

您可以隨時使用Where()方法以後過濾空值:

Where(u => u != null) 
相關問題