Categories
Programming

Linq Style Mapping for Single Objects

Linq is not just the go-to .NET library for handling IEnumerable data sources, it’s the inspiration for many successful and unsucessful attempts to reproduce the style in other languages. When you have a class full of Linq and you find yourself wanting to simply map a single object to something else, you’ll find yourself writing […]

Categories
Programming

Shorten Your Linq Expressions

There is an interesting style of Linq expression that I am seeing a lot in code, including open source projects. It isn’t a big deal, but it damages readability. It looks like this: var result = someEnumerable.Where(e => e.IsCondition).FirstOrDefault(); var result = someEnumerable.Where(e => e.IsCondition).SingleOrDefault(); var result = someEnumerable.Where(e => e.IsCondition).Count(); Can you spot it? […]

Categories
Programming

Get Argument Values From Linq Expression

If you even find yourself unpacking an expression in C#, you might find this useful. I found myself in need of obtaining a list of argument values from within an Expression expression that sometimes had chained method calls. For example, I needed to be able to get the arguments from all of the following… SomeMethod(() […]

Categories
Programming

Only Primitive Types or Enumeration Types are Supported in this Context

This error popped up and I’m sure that it is vague enough to catch me out again in the future. Additional information: Unable to create a constant value of type ‘System.Object’. Only primitive types or enumeration types are supported in this context. There are two common causes for this error. One is obvious and the […]

Categories
Programming

Conditionally Add Filters Only When a Value Is Supplied

If you are converting a series of optional filters in a UI into an IQueryable, you’ll find yourself writing a lot of if-statements to only add a filter if a value is supplied. if (myNumber!= 0) { query = query.Where(t => t.Number.Equals(myNumber)); } if (myName!= 0) { query = query.Where(t => t.Name.Equals(myName)); } I have […]

Categories
Programming

Getting the SQL Query From an Entity Framework IQueryable

If you have ever wanted to look inside an IQueryable in Entity Framework to see what query will be run, you’ll know that it is properly squirrelled away in there. On the whole, that’s a good thing because you shouldn’t care about it. Despite this, there are sometimes occasions where “never” doesn’t mean “never”. I […]

Categories
Programming

Real Linq Style Operations Using ECMAScript 6

There have been a few attempts to create versions of .NET’s LINQ extensions to JavaScript and TypeScript, but most of them involve operating on an array and returning an array. To be clear, it involves evaluating the result of the expression immediately and giving back the whole result immediately. This isn’t really analogous for LINQ, […]