Skip to content

Instantly share code, notes, and snippets.

@pedropmota
Created March 7, 2018 21:37
Show Gist options
  • Save pedropmota/bad39b9c7a9bb3f27bed8942c2f67772 to your computer and use it in GitHub Desktop.
Save pedropmota/bad39b9c7a9bb3f27bed8942c2f67772 to your computer and use it in GitHub Desktop.
C# method for getting all possible combinations of elements
/// <summary>
/// Gets all possible combinations of the specified list, based on the specified length of each resulting element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="length"></param>
/// <param name="check">Additional check before adding an element to the final result. (t1 = IEnumerable of T, t2 = T)</param>
/// <returns></returns>
static IEnumerable<IEnumerable<T>> GetCombinations<T>(IEnumerable<T> list, int length,
Func<IEnumerable<T>, T, bool> check = null)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetCombinations(list, length - 1, check).ToArray()
.SelectMany(t => list, (t1, t2) => {
if (check == null || (t1 != null && check(t1, t2)))
return t1.Concat(new T[] { t2 }).ToArray();
else
return null;
})
.Where(result => result != null)
.ToArray();
// Simple way (no check):
//.SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment