質問

I am using a Converter to convert a List<string> into a List<UInt32>

It does well, but when one of the array elements is not convertable, ToUint32 throw FormatException.

I would like to inform the user about the failed element.

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.
}

I am catching the FormatException but can't find if it contains the string name.

役に立ちましたか?

解決

You can catch exception inside the 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);
    }
}));

他のヒント

You could use the TryParse method:

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

Here is what I would use in this contest:

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

You could always use the Where() method to filter the null values later:

Where(u => u != null)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top