Skip to content

Instantly share code, notes, and snippets.

@egil
Created October 7, 2019 21:55
Show Gist options
  • Save egil/ebf28b8cb6ff427683bcafed78d6353a to your computer and use it in GitHub Desktop.
Save egil/ebf28b8cb6ff427683bcafed78d6353a to your computer and use it in GitHub Desktop.
A C# IList extension method that returns all combinations of the content of the list. See related question on StackOverflow: https://stackoverflow.com/questions/7802822/all-possible-combinations-of-a-list-of-values/40417765#40417765
using System;
using System.Collections.Generic;
public static class ListExtensions
{
public static IEnumerable<List<TInput>> AllCombinations<TInput>(this IList<TInput> list)
=> list.AllCombinations(() => new List<TInput>(), (list, item) => list.Add(item));
public static IEnumerable<TCombinationContainer> AllCombinations<TInput, TCombinationContainer>(
this IList<TInput> list,
Func<TCombinationContainer> combinationContainerFactory,
Action<TCombinationContainer, TInput> combinationAggregator)
{
if (list is null) throw new ArgumentNullException(nameof(list));
int comboCount = (int)Math.Pow(2, list.Count) - 1;
for (int i = 1; i <= comboCount; i++)
{
var combiContainer = combinationContainerFactory();
for (int j = 0; j < list.Count; j++)
{
if ((i >> j) % 2 != 0)
{
combinationAggregator(combiContainer, list[j]);
}
}
yield return combiContainer;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment