Usage Examples: CollectionExtensions.cs

Coordinator
Jul 19, 2009 at 9:07 PM
Edited Jul 19, 2009 at 9:15 PM

CollectionExtensions.cs

AddRange

List<string> items = new List<string>();
items.Add("a");
items.Add("b");
items.AddRange("c", "d", "e");

Average

int[] array = new int[] { 1, 2, 3, 4, 5 };
float average = array.Average(); -> results in 3

Combine

int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 4, 5, 6 };
int[] array3 = new int[] { 7, 8, 9 };
int[] combined = array1.Combine<int>(array2, array3);

ContainsAtLeast

List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
bool valid = list.ContainsAtLeast<int>(2);

ForEach

buttons.ForEach(b => b.Click());

GroupEvery

List<int> list = new List<int>();
for (int i = 0; i < 10; i++)
{
list.Add(i);
}
IEnumerable<int[]> groupedList = list.GroupEvery<int>(2);

IndexOf

List<string> items = new List<string>();
items.Push("a");
items.Push("b");
items.Push("c");
int index = items.IndexOf<string>("c");

IndexOf

List<string> items = new List<string>();
items.Push("a");
items.Push("b");
items.Push("c");
int index = items.IndexOf<string>("c", myComparer);

IndexOf

List<string> items = new List<string>();
items.Push("a");
items.Push("b");
items.Push("c");
int index = items.IndexOf<string>("c", 1);

IndexOf

List<string> items = new List<string>();
items.Push("a");
items.Push("b");
items.Push("c");
int index = items.IndexOf<string>("c", 1, myComparer);

IndexOfNextContaining

List<string> items = new List<string>();
items.Push("Hello, ");
items.Push("World!");
items.Push("How ");
items.Push("are ");
items.Push("you?");
int index = items.IndexOfNextContaining("re", 2);

IndexOfPrevious

List<string> items = new List<string>();
items.Push("a");
items.Push("b");
items.Push("c");
int indexOfA = items.IndexOfPrevious("a", 2);

IndexOfPreviousContaining

List<string> items = new List<string>();
items.Push("Hello, ");
items.Push("World!");
items.Push("How ");
items.Push("are ");
items.Push("you?");
int index = items.IndexOfPreviousContaining("Wor", 3);

IsNullOrEmpty

string[] array = new string[] { };
bool isEmpty = array.IsNullOrEmpty();-> results in true

IsNullOrEmpty

if (!list.IsNullOrEmpty())
{
// do operation involving list
}

Pop

var list = new List<int>();
for (int i = 1; i <= 10; i++)
{
list.Push(i);
}
while (list.Count > 0)
{
Console.WriteLine(list.Pop());
}

Push

var list = new List<int>();
for (int i = 1; i <= 10; i++)
{
list.Push(i);
}
while (list.Count > 0)
{
Console.WriteLine(list.Pop());
}

RemoveDuplicates

string[] array = new string[] { "test1", "test2", "test1" };
string[] filtered = array.RemoveDuplicates(); -> results in string[] { "test1", "test2" };

Slice

int[] array = new int[] { 1, 2, 3, 4, 5 };
int[] slice = array.Slice<int>(1, 3);