简体   繁体   中英

LINQ C# building an expression with anonymous type

I have BinaryTree<Student> DeserializedStudents and linq query:

var students = DeserializedStudents.OrderBy(testResult => testResult.Test_Result).
Select(cust => new { name = cust.Name, result = cust.Test_Result });

Can someone please tell me how to build an expression that is equal to this query?

With complex expressions, you can cheat and see what the compiler does:

Expression<Func<IEnumerable<Student>, IEnumerable<Student>>> expression = 
  query => query
    .OrderBy(testResult => testResult.Test_Result)
    .Select(cust => new { name = cust.Name, result = cust.Test_Result });

Just have a look at expression in a debugger.

BTW, LINQPad is very helpful for this.

You can use IQueryable interface implementation to auto-build your expression based on LinQ :

var query = DeserializedStudents.AsQueryable()
    .OrderBy(testResult => testResult.Test_Result)
    .Select(cust => new { name = cust.Name, result = cust.Test_Result });

var expression = query.Expression;

Like this?:

var students = from cust in DeserializedStudents
               orderby cust.Test_Result
               select new { name = cust.name, result = cust.Test_Result };

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