Refactor an ugly loop into LINQ

john_mm

I have the following peace of code, that factors an int to prime numbers:

    private static IEnumerable<int> Factor(int input)
    {
        IList<int> result = new List<int>();

        while (true)
        {
            var theSmallestDivisor = GetTheSmallestDivisor(input);
            if (theSmallestDivisor == 0)
            {
                result.Add(input);
                return result;
            }

            result.Add(theSmallestDivisor);
            input = input/theSmallestDivisor;
        }
    }

I'm looking for hints on how to improve it, possibly using LINQ.

Lucas Trzesniewski

Here's an iterator version:

private static IEnumerable<int> Factor(int input)
{
    while (true)
    {
        var theSmallestDivisor = GetTheSmallestDivisor(input);
        if (theSmallestDivisor == 0)
        {
            yield return input;
            yield break;
        }

        yield return theSmallestDivisor;
        input = input / theSmallestDivisor;
    }
}

LINQ would only make this code less readable in that particular case.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How do I refactor a ReadLine loop to Linq

From Dev

How can I refactor a set of ugly if statements?

From Dev

Refactor Linq query

From Dev

Refactor nested 'foreach' and 'If' to LINQ

From Dev

Linq Join and GroupBy refactor

From Dev

Refactor foreach and if's to Linq

From Dev

How to refactor LINQ query

From Dev

Refactor Linq query

From Dev

Refactor foreach and if's to Linq

From Dev

Refactor foreach to for loop

From Dev

Refactor loop into a single line?

From Dev

Linq Expression Refactor Duplicate Code

From Dev

Linq Expression Refactor Duplicate Code

From Dev

Refactor function with nested for loop - Javascript

From Dev

How do I refactor this loop?

From Dev

How do I refactor this loop?

From Dev

Dart - How to refactor this loop with copywith?

From Dev

Refactor foreach loop to List<T>.ForEach(...)

From Dev

Howto refactor for loop with Service call into Stream?

From Dev

Refactor part of a program to a loop to make it smaller

From Dev

Refactor regular for loop into angular.forEach

From Dev

Refactor for-loop with side effects to stream

From Dev

Refactor function with for loop and multiple if else statements

From Dev

How to refactor for loop method to break when there are no elements

From Dev

LINQ - Refactor .Contains comparison on IEnumerable<string> to be case sensitive

From Dev

How do I refactor a recursion occurring in a for loop to make it a tail call?

From Dev

How to refactor my nested 3 deep foreach loop

From Dev

Python declarative loop refactor (need access multiple elements)

From Dev

How can I refactor this for loop to adhere to the DRY principle?