KallDrexx
KallDrexx

Reputation: 27813

What is TKey in System.Linq.Expressions.Expression<Func<TSource,TKey>>?

I'm trying to store expressions required by Linq OrderBy clauses in data structures, so I can just go query = query.OrderBy(MySortExpression);

OrderBy takes System.Linq.Expressions.Expression<Func<TSource,TKey>> as a parameter. TSource is the entity type you are sorting on, but what type is TKey supposed to be?

Upvotes: 1

Views: 3151

Answers (3)

Ivo
Ivo

Reputation: 8352

TKey is the type of the return type of the expression. For instance:

users.OrderBy(user => user.Name); 

As Name is string, the type will be System.Linq.Expressions.Expression<Func<User,string>>

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726709

TKey is a generic type argument denoting the type of the expression on which you sort. For example, if you sort strings by length, TSource will be string, and TKey will be int, as in the code below:

string [] myStrings = new[] {"quick", "brown", "fox", "jumps"};
var ordered = myStrings.OrderBy(s => s.Length);

Upvotes: 5

faester
faester

Reputation: 15086

The TKey is not bound to a specific type. Usually it is a projection of a property to a primitive type to enable sorting.

Assuming a Person with a BirthYear property you would select

 persons.OrderBy(p => p.BirthYear);

Upvotes: 2

Related Questions