我有一个返回类型对象的“GetTransactions”方法:
IList<ApplicationTransaction>
这是一个 ApplicationTransaction:
public partial class ApplicationTransaction
{
public int TransactionId { get; set; }
public int ApplicationId { get; set; }
public string Event { get; set; }
public System.DateTime CreatedOn { get; set; }
public virtual Application Application { get; set; }
}
如何转换此 LINQ 查询:
return (from t in GetTransactions().OfType<ApplicationTransaction>()
where t.Event == transactionType.ToString()
select t).FirstOrDefault();
进入流利的语法?
这行不通 - 我有什么不明白的?
return GetTransactions().OfType<ApplicationTransaction>().Where(t.Event == transactionType.ToString().FirstOrDefault();
最佳答案
您需要在 where 语句中为 lambda 参数:
return GetTransactions()
.OfType<ApplicationTransaction>()
.Where(t => t.Event == transactionType.ToString())
.FirstOrDefault();
(注意 t =>
部分定义了一个新的表达式作用域,而不是直接尝试访问变量“t”)
如果您要选择整个实体,则不需要单独选择。
我还建议使用我在答案中使用的多行布局来更好地理解查询并发现潜在问题,例如 @nvoigt 提到的缺少括号问题。
关于c# - 如何以流畅的语法编写此 LINQ 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39032249/