View Category

Define an empty list

Assign the variable "list" to a list with no elements
csharp
var list = new List<object>();

Define a static list

Define the list [One, Two, Three, Four, Five]
csharp
IList<string> list = new string[]{"One","Two","Three","Four","Five"};

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
csharp
using System.Collections.Generic;
public class JoinEach {
public static void Main() {
var list = new List<string>() {"Apple", "Banana", "Carrot"};
System.Console.WriteLine( string.Join(", ", list.ToArray()) );
}
}

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
csharp
using System.Collections.Generic;
using System.Linq;

public class CSharpListToEnglishList {
public string JoinAsEnglishList (List<string> words) {
switch (words.Count) {
case 0: return "";
case 1: return words[0];
case 2: return string.Format("{0} and {1}", words.ToArray());
default:
return JoinAsEnglishList( new List<string>() {
string.Join(", ", words.Take(words.Count - 1).ToArray()) + ",",
words.Last()
});
}
}
// Driver...
public static void Main() {
var joiner = new CSharpListToEnglishList();
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot", "Orange" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Apple", "Banana", "Carrot" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "One", "Two" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>() { "Lonely" }) );
System.Console.WriteLine(
joiner.JoinAsEnglishList(new List<string>()) );
}
}

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
csharp
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };

// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
csharp
List<String> values = new List<string> {"andrew", "bob", "chris", "bob"};

var duplicates = values
.GroupBy(i => i)
.Where(j => j.Count() > 1)
.Select(s => s.Key);
foreach (var duplicate in duplicates)
{
Console.WriteLine(duplicate);
}

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
csharp
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
List<string> list = new List<string>(items);
string third = list[2]; // "Three"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of indexing if you are using Lists.
string[] items = new string[] { "One", "Two", "Three", "Four", "Five" };
IEnumerable<string> list = new List<string>(items);
string third = list.ElementAt(2); // Three

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
csharp
string[] items = new string[] { "Red", "Green", "Blue" };
List<string> list = new List<string>(items);
string last = list[list.Count - 1]; // "Blue"
// Make sure you import the System.Linq namespace.
// This is not the preferred way of finding the last element if you are using Lists.
string[] items = new string[] { "Red", "Green", "Blue" };
IEnumerable<string> list = new List<string>(items);
string last = list.Last(); // "Blue"

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
csharp
// Make sure you import the System.Linq namespace.
// This example uses arrays as the underlying implementation, but any IEnumerable type can be used - including List.
IEnumerable<string> beans = new string[] { "beans", "mung", "black", "red", "white" };
IEnumerable<string> colors = new string[] { "black", "red", "blue", "green" };
var intersect = beans.Intersect(colors); // ['red', 'black']

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
csharp
using System.Collections.Generic;
using System.Linq;
public class UniqueElements {
public static void Main() {
var list = new List<int>() { 18, 16, 17, 18, 16, 19, 14, 17, 19, 18 };
var uniques = list.Distinct();
}
}

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
csharp
class Solution1516
{
static void Main()
{
List<string> fruit = new List<string>() { "Apple", "Banana", "Carrot" };
fruit.RemoveAt(0);
}
}

Remove the last element of a list

csharp
List<string> fruits = new List() { "apple", "banana", "cherry" };
fruits.RemoveAt(fruits.Length - 1);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
csharp
var lst = new LinkedList<String>(new String[] {"apple", "orange", "grapes", "banana"});
lst.AddLast(lst.First());
lst.DeleteFirst();

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
csharp
String[] first = { "Bruce", "Tommy Lee", "Bruce" };
String[] last = { "Willis", "Jones", "Lee" };
int[] years = { 1955, 1946, 1940 };
var actors = first.Zip(last, (f, l) => Tuple.Create(f, l)).Zip(years, (t, y) => Tuple.Create(t.Item1, t.Item2, y)).ToArray();
Debug.Assert(actors[1].Equals(Tuple.Create("Tommy Lee", "Jones", 1946)));

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
csharp
using System;
using System.Collections.Generic;
using System.Linq;

namespace Combinations
{
class Program
{
public static void Main(string[] args)
{
// Define the given lists
// Since List`1 implements the interface IEnumerable`1, this can easily be redefined as List`1.
IEnumerable<string> suites = new string[] { "H", "D", "C", "S" };
IEnumerable<string> faces = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

// LINQ Query to perform a Cartesian product and create an anonymous type to hold the results.
// "var" is required to define this as an IEnumerable`1
var deck =
from suite in suites // For each suite in suites
from face in faces // Match it with a face in face.
select new
{
Suite = suite,
Face = face
};

// Verify the count (uses LINQ extension)
if (deck.Count() == 52)
{
Console.WriteLine("Count matches!");
}

// Verify that the Ace of Hearts is in the deck (uses LINQ extension)
if (deck.Contains(new {Suite = "H", Face = "A"}))
{
Console.WriteLine("Ace of Hearts found!");
}

// Example of how to iterate through the list.
// "var" here is required since we are using an anonymous type
foreach(var card in deck)
{
Console.WriteLine("Suite: {0} Face: {1}", card.Suite, card.Face);
}

// If you desire to work with a List`1, you can convert this to a normal list at any time:
Console.WriteLine("\nConverting to list!");
var list = deck.ToList();
Console.WriteLine("Suite: {0} Face: {1}", list[5].Suite, list[5].Face);
Console.WriteLine("List count: {0}", list.Count); // 52

Console.ReadLine();
}
}
}

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
csharp
using System.Collections.Generic;
public class OperationOnEach {
public static void Main() {
var list = new List<string>() { "ox", "cat", "deer", "whale" };
list.ForEach( System.Console.WriteLine );
}
}

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
csharp
using System;
using System.Collections.Generic;
using System.Linq;

// AFAIK, there just isn't a good way to do this in C#
public class ListSplitter {
public static bool IsNumeric(object o) {
var d = new Decimal();
return decimal.TryParse(o.ToString(), out d);
}
public static void Main() {
var list = new List<object>() { "foo", DateTime.Now, 1, "bar", 2.4 };

// the Where method does the work...
var numbers = list.Where( el => IsNumeric(el) );
var nonNumbers = list.Where( el => ! IsNumeric(el) );
}

}

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.