Generate all combinations for a list of strings

前端 未结 4 916
情歌与酒
情歌与酒 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 09:01

    One more recursive solution. From AllCombinations in below code, you will get all possible combinations. Logic:

    1. Starting with one element.
    2. Generate all possible combinations with it.
    3. Move to next element and begin with step 2 again.

    Code:

    public class Combination
    {
        private IEnumerable list { get; set; }
        private int length;
        private List> _allCombination;
    
        public Combination(IEnumerable _list)
        {
            list = _list;
            length = _list.Count();
    
            _allCombination = new List>();
        }
    
        public IEnumerable> AllCombinations
        {
            get
            {
                GenerateCombination(default(int), Enumerable.Empty());
    
                return _allCombination;
            }
        }
    
        private void GenerateCombination(int position, IEnumerable previousCombination)
        {
            for (int i = position; i < length; i++)
            {
                var currentCombination = new List();
                currentCombination.AddRange(previousCombination);
                currentCombination.Add(list.ElementAt(i));
    
                _allCombination.Add(currentCombination);
    
                GenerateCombination(i + 1, currentCombination);
    
            }
        }
    }
    

提交回复
热议问题