Created
January 29, 2015 18:32
-
-
Save RobSeder/f9c8ca9041d4aa549729 to your computer and use it in GitHub Desktop.
Source code for this blog post: http://blog.robseder.com/2015/01/29/generics-lambda-expressions-and-linq/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Customer | |
{ | |
public Guid CustomerId { get; set; } | |
public String FirstName { get; set; } | |
public String LastName { get; set; } | |
public override string ToString() | |
{ | |
return String.Format("{0} {1}", FirstName, LastName); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
IEnumerable<Customer> customersRaw = GetAllCustomers(); | |
Debug.WriteLine("Raw, unsorted:"); | |
foreach (Customer customer in customersRaw) | |
{ | |
Debug.WriteLine(customer); | |
} | |
Debug.WriteLine("-----------------------------------"); | |
IEnumerable<Customer> customersFiltered = | |
GetByFilter(item => item.LastName.Contains("i")); | |
Debug.WriteLine("Customers with 'i' in their last name:"); | |
foreach (Customer customer in customersFiltered) | |
{ | |
Debug.WriteLine(customer); | |
} | |
Debug.WriteLine("-----------------------------------"); | |
IEnumerable<Customer> customersOrdered = | |
GetAndSort(item => item.FirstName); | |
Debug.WriteLine("Customers sorted by first name:"); | |
foreach (Customer customer in customersOrdered) | |
{ | |
Debug.WriteLine(customer); | |
} | |
Debugger.Break(); | |
} | |
private static IEnumerable<Customer> GetAllCustomers() | |
{ | |
List<Customer> customers = new List<Customer> | |
{ | |
new Customer() {CustomerId = Guid.NewGuid(), FirstName = "Adam", LastName = "Zelda"}, | |
new Customer() {CustomerId = Guid.NewGuid(), FirstName = "Carlie", LastName = "Xavier"}, | |
new Customer() {CustomerId = Guid.NewGuid(), FirstName = "Brianna", LastName = "Yankovic"} | |
}; | |
return customers; | |
} | |
private static IEnumerable<Customer> GetByFilter(Func<Customer, Boolean> whereClause) | |
{ | |
if (whereClause == null) | |
throw new ArgumentNullException("whereClause"); | |
IEnumerable<Customer> customers = GetAllCustomers(); | |
return customers.Where(whereClause); | |
} | |
private static IEnumerable<Customer> GetAndSort<TKey>(Func<Customer, TKey> orderBy) | |
{ | |
if (orderBy == null) | |
throw new ArgumentNullException("orderBy"); | |
IEnumerable<Customer> customers = GetAllCustomers(); | |
return customers.OrderBy(orderBy); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment