Someone can help me to convert this Python code to C#?


#1

Someone can help me to convert this Python code to C# ?

I’m trying to use IEnumerable<IEnumerable> for solve this problem but I’m stuck, someone can give me any recommendation ?

def example(*args, repeat=1):
  pools = [tuple(pool) for pool in args] * repeat
  print(pools)

example('ABCD', 'xy')
example('ABCD', 'xy', repeat=2)
example(range(2), repeat=3)
example([[1],2,3],[4,5,6],[7,8,9], repeat=2)

Output:

[('A', 'B', 'C', 'D'), ('x', 'y')]
[('A', 'B', 'C', 'D'), ('x', 'y'), ('A', 'B', 'C', 'D'), ('x', 'y')]
[(0, 1), (0, 1), (0, 1)]
[([1], 2, 3), (4, 5, 6), (7, 8, 9), ([1], 2, 3), (4, 5, 6), (7, 8, 9)]

#2

So, what did you already tried to do?

I think LINQ can help you to solve your problem like

Simple Example
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Example("Hello", "World"));
        Console.WriteLine(Example(123, 456));
    }
    
    private static string Example(params object[] args)
    {
        var sb = new StringBuilder("[");
        var text = args.Select(s => s.ToString().Select(c => c.ToString()).Aggregate((s1, s2) => $"{s1}, {s2}"))
                   .Aggregate((s1, s2) => $"({s1}), ({s2})");

        sb.Append(text);
        sb.Append("]");
        return sb.ToString();
    }
}

Also you can create an overloads for your method, that can receive an array or ienumerable of something and repeat count.

c# can’t give you the same flexibility because of it’s type system (it’s strong strictly typed language).


.NET Foundation Website | Blog | Projects | Code of Conduct