How to create a dynamic LINQ join extension method

I’ve fixed it myself now. It was a schoolboy error passing too many parameters to the CreateQuery(… ) call. Paste the following code into the Dynamic.cs file within the DynamicQueryable class for a dynamic Join extension method. You can find the source for the DynamicQuery sample project at http://code.msdn.microsoft.com/csharpsamples. Enjoy. public static IQueryable Join(this IQueryable … Read more

Find() vs. Where().FirstOrDefault()

Where is the Find method on IEnumerable<T>? (Rhetorical question.) The Where and FirstOrDefault methods are applicable against multiple kinds of sequences, including List<T>, T[], Collection<T>, etc. Any sequence that implements IEnumerable<T> can use these methods. Find is available only for the List<T>. Methods that are generally more applicable, are then more reusable and have a … Read more

Recursive control search with LINQ

Take the type/ID checking out of the recursion, so just have a “give me all the controls, recursively” method, e.g. public static IEnumerable<Control> GetAllControls(this Control parent) { foreach (Control control in parent.Controls) { yield return control; foreach(Control descendant in control.GetAllControls()) { yield return descendant; } } } That’s somewhat inefficient (in terms of creating lots … Read more

Sorting a list using Lambda/Linq to objects

This can be done as list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) ); The .NET framework is casting the lambda (emp1,emp2)=>int as a Comparer<Employee>. This has the advantage of being strongly typed. If you need the descending/reverse order invert the parameters. list.Sort( (emp1,emp2)=>emp2.FirstName.CompareTo(emp1.FirstName) );