How to iterate lists with different lengths to find all permutations?

后端 未结 3 1805
长发绾君心
长发绾君心 2020-12-22 07:27

This one should not be too hard but my mind seems to be having a stack overflow (huehue). I have a series of Lists and I want to find all permutations they can be ordered in

3条回答
  •  没有蜡笔的小新
    2020-12-22 07:40

    Try this:

    Func, IEnumerable> combine = null;
    combine = xs =>
        xs.Skip(1).Any()
        ? xs.First().SelectMany(x => combine(xs.Skip(1)), (x, y) => String.Format("{0}{1}", x, y))
        : xs.First().Select(x => x.ToString());
    
    var strings = new [] { "AB", "12", "$%" };
    
    foreach (var x in combine(strings))
    {
        Console.WriteLine(x);
    }
    

    That gives me:

    A1$
    A1%
    A2$
    A2%
    B1$
    B1%
    B2$
    B2%
    

提交回复
热议问题