简体   繁体   English

LINQ C#构建一个匿名类型的表达式

[英]LINQ C# building an expression with anonymous type

I have BinaryTree<Student> DeserializedStudents and linq query: 我有BinaryTree<Student> DeserializedStudents和linq查询:

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. 只需查看调试器中的expression

BTW, LINQPad is very helpful for this. 顺便说一句, LINQPad对此非常有帮助。

You can use IQueryable interface implementation to auto-build your expression based on LinQ : 您可以使用IQueryable接口实现基于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 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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