Преобразование FormatException

Я использую конвертер для преобразования 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, но не могу найти, если он содержит имя строки.

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);
    }
}));

Вы могли бы использовать 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;
});

Вот что я бы использовал в этом конкурсе:

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)
Другие вопросы по тегам