简体   繁体   中英

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?

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);

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>>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM