using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] names = { "A1", "B123", "C123123", "E", "W" };
IEnumerable<string> sequence = names
.Where(n => n.Length < 6)
.Select(n => n);
foreach (string name in sequence) {
Console.WriteLine("{0}", name);
}
}
}
LINQ
To remove all vowels from a string.
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass {
public static void Main() {
IEnumerable<char> query = "Not what you might expect";
query = query.Where(c => c != 'a');
query = query.Where(c => c != 'e');
query = query.Where(c => c != 'i');
query = query.Where(c => c != 'o');
query = query.Where(c => c != 'u');
foreach (char c in query) Console.Write(c);
}
}
Where Prototype
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"A", "Ar", "B", "Bu", "C", "Cleveland"};
IEnumerable<string> sequence = presidents.Where(p => p.StartsWith("C"));
foreach (string s in sequence)
Console.WriteLine("{0}", s);
}
}
An Example of Collection Initialization
using System.Collections.Generic;
using System;
public class MainClass {
public static void Main() {
List<string> presidents = new List<string> { "AAAA", "BBBBBB", "CCCCCCCC" };
foreach (string president in presidents) {
Console.WriteLine(president);
}
}
}
Instantiating and Initializing an Anonymous Type Using Object Initialization
using System;
public class MainClass {
public static void Main() {
var address = new {
address = "First Street",
city = "Vancouver",
state = "GA",
postalCode = "99999"
};
Console.WriteLine("address = {0} : city = {1} : state = {2} : zip = {3}",
address.address, address.city, address.state, address.postalCode);
Console.WriteLine("{0}", address.GetType().ToString());
}
}
An Anonymous Type Assigned to a Variable Declared with the var Keyword
using System;
public class MainClass {
public static void Main() {
var unnamedTypeVar = new { firstArg = 1, secondArg = "Joe" };
Console.WriteLine(unnamedTypeVar.firstArg + ". " + unnamedTypeVar.secondArg);
}
}
Anonymous Types
using System;
using System.Collections.Generic;
using System.Diagnostics;
class MainClass{
static void DisplayProcesses(Func<Process, Boolean> match) {
var processes = new List<Object>();
foreach (var process in Process.GetProcesses()) {
if (match(process)) {
processes.Add(new {
process.Id, Name = process.ProcessName,
Memory = process.WorkingSet64
});
}
}
}
static void Main(string[] args) {
DisplayProcesses(process => process.WorkingSet64 >= 20 * 1024 * 1024);
}
}