Search code examples
c#linqout

LINQ: transform enumerable until end condition is met, and return if the end condition was met


I have a string enumerable strArr. I want to convert all entries into int as long as that is possible, and when an entry is not convertible to int, enumeration should stop. I also want to return a bool that tells me if converting all entries was possible or not.

So what I am looking for is kind of the enumerable version of int.TryParse (it returns both a bool if converting was successful and the converted value).

I thought it could be done with LINQ, but I can't figure it out. Here are my thoughts:

strArr.
    Select(s => { bool b = int.TryParse(s, out int i); return (i, b); }).
        // returns both the converted int value and the parsing bool for each entry
    TakeWhile(ib => ib.b).
        // will stop when the first parsing bool was false
    Select(ib => i).ToArray();
        // will only take the ints from the (int, bool) pairs and return an array

This solution will give me the converted entries as an array, but it will not tell me if conversion was successful. I need a way to out either the bool or the enumerable, but how?

I know I could compare lengths of strArr and the returned int array to see if conversion was successful. But I want to learn about LINQ usage, not just solve the problem at hand (I could always just do some looping and never use LINQ at all).


Solution

  • Thanks to mjwills' little hint I got it:

    bool parseSuccess = true;
    int[] intArr = strArr.
        Select(s => { parseSuccess &= int.TryParse(s, out int i); return i; }).
        TakeWhile(i => parseSuccess).ToArray();