CRM 2011: How to compare CRM fields with Linq

Well, you can’t. As Microsoft states here:

In a where clause, the left side of the clause must be an attribute name and the right side of the clause must be a value. You cannot set the left side to a constant. Both the sides of the clause cannot be constants.

So, you cannot do something like:

from a in context.AccountSet
where a.ModifiedOn.Value > a.CreatedOn.Value
select a.Name

Trying this will get you a nice and sweet error message explaining to you that:

InvalidOperationException: variable ‘<> [...]¬†referenced from scope ”, but it is not defined

So if you want to do it, you have to retrieve your data and filter it in memory using the Where extension method:

var resultsToFilter = (from a in context.AccountSet
select a.Name, a.ModifiedOn, a.CreatedOn)
.ToList();

var filteredResults = resultsToFilter
.Where(x => x.ModifiedOn.Value > a.CreatedOn.Value) ;

And there you have it.