Skip to content

Instantly share code, notes, and snippets.

@morbidcamel101
Last active August 29, 2015 14:09
Show Gist options
  • Save morbidcamel101/7dc784b4f41a553c7d21 to your computer and use it in GitHub Desktop.
Save morbidcamel101/7dc784b4f41a553c7d21 to your computer and use it in GitHub Desktop.
LINQ utility functions like IndexOf, ForEach, ItemAt that should have been included in LINQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static class LinqUtil
{
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
{
foreach (T item in items)
{
collection.Add(item);
}
}
public static void AddRangeIf<T>(this ICollection<T> collection, IEnumerable<T> items, Func<T, bool> predicate)
{
foreach (var item in items) {
if (!predicate (item))
continue;
collection.Add (item);
}
}
public static string ToListText<T>(this IEnumerable<T> values)
{
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (T val in values)
{
if (i++ > 0)
builder.Append(',');
builder.Append(val != null ? Convert.ToString(val) : "NULL");
}
return builder.ToString();
}
public static void ForEach<T>(this IEnumerable<T> enumerator, Action<T> action)
{
foreach (T element in enumerator)
{
action(element);
}
}
public static int IndexOf<T>(this IEnumerable<T> enumerator, T item)
{
int index = 0;
foreach (var it in enumerator)
{
if (it.Equals(item))
return index;
index++;
}
return -1;
}
public static T ItemAt<T>(this IEnumerable<T> enumerator, int index)
{
int idx = 0;
foreach (var item in enumerator)
{
if (idx++ == index)
return item;
}
return default(T);
}
public static void Shuffle<T>(this T[] array, int seed = 0)
{
System.Random rng = (seed != 0) ? new System.Random(seed) : new System.Random();
int n = array.Length;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = array[k];
array[k] = array[n];
array[n] = value;
}
}
public static T[] WithElement<T>(this T[] array, T element)
{
if (array == null)
{
return array = new T[] { element };
}
int index = array.Length;
Array.Resize(ref array, index+1);
array[index] = element;
return array;
}
public static T[] Remove<T>(this T[] items, T item)
{
var list = items.ToList();
for(int i = list.Count-1; i >= 0; i--)
{
if (list[i].Equals(item))
{
list.RemoveAt(i);
break;
}
}
return list.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment