Generate all combinations for a list of strings

前端 未结 4 924
情歌与酒
情歌与酒 2020-12-05 08:14

I want to generate a list of all possible combinations of a list of strings (it\'s actually a list of objects, but for simplicity we\'ll use strings). I need this list so th

4条回答
  •  天涯浪人
    2020-12-05 08:57

    You can make in manually, using the fact that n-bit binary number naturally corresponds to a subset of n-element set.

    private IEnumerable constructSetFromBits(int i)
    {
        for (int n = 0; i != 0; i /= 2, n++)
        {
            if ((i & 1) != 0)
                yield return n;
        }
    }
    
    List allValues = new List()
            { "A1", "A2", "A3", "B1", "B2", "C1" };
    
    private IEnumerable> produceEnumeration()
    {
        for (int i = 0; i < (1 << allValues.Count); i++)
        {
            yield return
                constructSetFromBits(i).Select(n => allValues[n]).ToList();
        }
    }
    
    public List> produceList()
    {
        return produceEnumeration().ToList();
    }
    

提交回复
热议问题