List.ConvertAll and Exception

if ConvertAll throws an exception for one element, can I just skip this element and move on to the next element?

+3
source share
3 answers

No. The exception will need to be handled somewhere. If you expect that there will be exceptions in the converter, and this is normal for the application, you should have a try-catch inside the converter (the following code example will return nullfor failed conversions):

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

List<int?> converted = input.ConvertAll(s =>
{
    int? result = null;
    try
    {
        result = int.Parse(s);
    }
    catch (Exception) { }

    return result;
});

(yes, I know what I should have used int.TryParse, but that would not throw an exception ...)

However, the use of such exceptions always gives the smell of a workaround, and I do not want to have anything in my code.

+6

throwing ConvertAll, , " ". - :

public static void Main(string[] args)
{
    var integers = new List<int>() { 1, 2, -5 };
    Converter<int, string> converter = x =>
    {
        if (x < 0)
            throw new NotSupportedException();

        return x.ToString();
    };

    // This code would throw
    //var result1 = integers.ConvertAll(converter).ToArray();
    //Console.WriteLine(String.Join(Environment.NewLine, result1));

    // This code ignores -5 element
    var result2 = RobustEnumerating(integers, converter).ToArray();
    Console.WriteLine(String.Join(Environment.NewLine, result2));
}

public static IEnumerable<K> RobustEnumerating<T, K>(IEnumerable<T> input,
    Converter<T, K> converter)
{
    List<K> results = new List<K>();
    foreach (T item in input)
    {
        try
        {
            results.Add(converter(item));
        }
        catch { continue; }
    }
    return results;
}

null , .

+1

, , . , , ConvertAll:

List<UnconvertedType> unconverted;

// do something to populate unconverted

List<ConvertedType> converted = unconverted.
    Where(ut => ut != null).
    ToList().
    ConvertAll<ConvertedType>(ut => ut as ConvertedType);

, , try/catch.

+1

Source: https://habr.com/ru/post/1740008/


All Articles