我正在使用转换器将List<string>转换为List<UInt32>
它做得很好,但是当其中一个数组元素不可转换时,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,但找不到它是否包含字符串名称。
发布于 2013-01-14 01:00:15
您可以在lambda中捕获异常:
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);
}
}));发布于 2013-01-14 00:58:10
您可以使用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;
});发布于 2013-01-14 01:20:22
下面是我在这场比赛中使用的内容:
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)https://stackoverflow.com/questions/14305788
复制相似问题