Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop to linq

Tags:

c#

linq

Is there any way to accumulate something using linq.

Initial code :

Something oneItem;
List<Something> allItems;
while ((oneLine = _generator.GenerateSomething()) != null)
    allItems.Add(_generator.CurrentItem);

I would like something like :

var allItems = Enumerable.Take( ()=>_generator.GenerateSomething()).While(item=>item !=null).ToList();

Actually, it would have been very good if generator implemented IEnumerable, I would have use it this way :

var allItems = _generator.TakeWhile(item !=null);

This last one is really easy to understand, I would like to approach it (I can use a kind of wrapper that generate a machine state given a production method (_generator.GenerateSomething()) and a stop condition (item == null). But I can not write this additional class for some reason).

like image 251
Toto Avatar asked Sep 17 '26 18:09

Toto


1 Answers

Write a function that is an equivalent to File.ReadLines in concept. Abstract away the code for reading lines from the console once, so that it can be reused.

public static IEnumerable<string> ReadLinesFromConsole()
{
    while (true)
    {
        var next = Console.ReadLine();
        if (next == null)
            yield break;
        yield return next;
    }
}

That said, if you really want to generalize it, you can. What you have here is a simple generator accepting a function.

public static IEnumerable<T> Generate<T>(Func<T> generator)
{
    while (true)
        yield return generator();
}

This allows you to write the code that you had in your example:

var allLines = Generate(() => Console.ReadLine())
    .TakeWhile(line => line != null);
like image 54
Servy Avatar answered Sep 20 '26 18:09

Servy