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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With