Conditional “orderby” sort order in LINQ

If you build the expression incrementally you can do this. Generally easier using expressions rather than comprehension expressions: var x = widgets.Where(w => w.Name.Contains(“xyz”)); if (flag) { x = x.OrderBy(w => w.property); } else { x = x.OrderByDescending(w => w.property); } (Assuming the Widget’s property is basis of sort since you don’t list one.)

How to group dates by week?

The fundamental question here is how to project a DateTime instance into a week of year value. This can be done using by calling Calendar.GetWeekOfYear. So define the projection: Func<DateTime, int> weekProjector = d => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear( d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday); You can configure exactly how the “week number” is determined by tweaking the parameters in the … Read more

Using LINQ to find item in a List but get “Value cannot be null. Parameter name: source”

The error you receive is from another method than the one you show here. It’s a method that takes a parameter with the name “source”. In your Visual Studio Options dialog, disable “Just my code”, disable “Step over properties and operators” and enable “Enable .NET Framework source stepping”. Make sure the .NET symbols can be … Read more

Strange LINQ To Entities Exception

This is a guess, but I think your anonymous type might be attempting to duck-type to an enum when you’ve got more than two queries. If that’s happening, then you’ll get this complaint about not implementing IConvertible, as enum implements IConvertible, and your anonymous type (now derrived from enum) does not implement the interface.