There have been times where I've had functionality I wanted to share with EF LINQ commands, and also in different places when dealing with just a single object in memory. Being able to share an expression in these two instances could be useful as to not duplicate logic.
Below I've got a dummy example where in a deliberately roundabout way I use an expression on a single object, but I was wondering if there is a sensible, succinct and clean way to just directly apply an expression to an object, or are expressions designed to be used explicitly in LINQ collection situations?
//Silly non practical example to show LINQ working
public static void Main(string[] args)
{
const string testString = "Test";
var length = testString.SingleSelect(GetCount);
Console.WriteLine(length);
}
private static T2 SingleSelect<T1, T2>(this T1 input, Expression<Func<T1, T2>> expression)
{
return new List<T1> { input }.AsQueryable().Select(expression).First();
}
private static Expression<Func<string, int>> GetCount => input => input.Length;