Skip to content

Instantly share code, notes, and snippets.

@musicm122
Created August 20, 2018 13:38
Show Gist options
  • Save musicm122/6b92f6b0d47ad5bd41e0b92a655b8ac5 to your computer and use it in GitHub Desktop.
Save musicm122/6b92f6b0d47ad5bd41e0b92a655b8ac5 to your computer and use it in GitHub Desktop.
void Main()
{
// Write code to test your extensions here. Press F5 to compile and run.
}
public static class MyExtensions
{
// Write custom extension methods here. They will be available to all queries.
public static bool IsNumeric(this string theValue)
{
long retNum;
return long.TryParse(theValue, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
}
}
// You can also define non-static classes, enums, etc.
public static class CollectionExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
//https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n?page=1&tab=votes#tab-top
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements)
{
return elements.Count() == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(elements.Count() - 1).Select(c => (new[] { e }).Concat(c)));
}
//https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n?page=1&tab=votes#tab-top
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment