Home > other >  C# Equivalent of Python's itertools.cycle [closed]
C# Equivalent of Python's itertools.cycle [closed]

Time:10-02

am trying to write similar code in c#

userdata_ = open(user_data.txt)
userdata = userdata_.readlines()
userdata_.close()
userdata = iter(map(lambda x: x.strip(), userdata))
userdata = itertools.cycle(userdata

)

now I can use this userdata like a generator and call Next(userdata) to get the next value in infinite loop

CodePudding user response:

I'm not a Python user. If this works the way I think it does it's not built into C# directly, but you can write a simple (or at least brief) helper method for C# method to get the same kind of result:

public static IEnumerable<T> Cycle(this IList<T> items)
{
    while(true) foreach(T item in items) yield return item;
}

And then use it with a file like this:

var userdata = File.ReadAllLines("user_data.txt").Cycle();

Note this requires loading the entire file into memory, which might be a problem for larger files. We can do better by combining this all into one method:

public IEnumerable<string> CycleFile(string fileName)
{
   while (true) foreach(var line in File.ReadLines(fileName)) yield return line;
}

This will only ever try to load one line into memory at a time, and has the added advantage of re-opening the file after each time through. You may want to check how file system locking works for this scenario, though. Reading the file in a shared mode may require a little more work (StreamReader with the right FileMode rather than just File.ReadLines()).

As with any IEnumerable, you can use the underlying Enumerator object directly. Here's an example:

var userdata = File.ReadAllLines("user_data.txt").Cycle().GetEnumerator();
while (true)
{ 
    Thread.Sleep(1000);
    userdata.MoveNext();
    Console.WriteLine(userdata.Current);
}

CodePudding user response:

You may consider using the GetEnumerator() method which returns an enumerator which can be used to attempt to retrieve the next value in the sequence until the end is reached.

IEnumerable<string> userdata = GetUserData();
IEnumerator userdataEnumerator = userdata.GetEnumerator();

do
{
   string cur = userdataEnumerator.Current;
   // do something with cur
}
while (userdataEnumerator.MoveNext());
  •  Tags:  
  • c#
  • Related