C# 可数返回优先
我有以下代码:C# 可数返回优先,c#,linq,C#,Linq,我有以下代码: public IEnumerable<Report> GetReport(int reportId) { var dbReport = dbContext.ReportsTbl.Where(w =>w.ID == reportId); return dbReport; } 公共IEnumerable GetReport(int reportId) { var dbReport=dbContext.Repo
public IEnumerable<Report> GetReport(int reportId)
{
var dbReport = dbContext.ReportsTbl.Where(w =>w.ID == reportId);
return dbReport;
}
公共IEnumerable GetReport(int reportId)
{
var dbReport=dbContext.ReportsTbl.Where(w=>w.ID==reportId);
返回dbReport;
}
我喜欢做的是让我们先到
如果我这样做:
public IEnumerable<Report> GetReport(int reportId)
{
var dbReport = dbContext.ReportsTbl.First(w =>w.ID == reportId);
return dbReport;
}
公共IEnumerable GetReport(int reportId)
{
var dbReport=dbContext.ReportsTbl.First(w=>w.ID==reportId);
返回dbReport;
}
我如何让它先做()。它抱怨它是IEnumerable。您需要更改方法签名以仅返回单个对象而不是集合:
public Report GetReport(int reportId)
{
var dbReport = dbContext.ReportsTbl.First(w =>w.ID == reportId);
return dbReport;
}
如果出于某种原因,您确实想要一个只包含第一个元素的集合,您可以使用
.Take(1)
而不是first
first
将第一个元素作为类型Report
返回。因为它只有一个项,所以不返回可枚举项
您有两个选择:
public Report GetReport(int reportId)
{
var dbReport = dbContext.ReportsTbl.First(w =>w.ID == reportId);
return dbReport;
}
本例只返回一个报告,而不是一堆(可枚举的)报告
public IEnumerable<Report> GetReport(int reportId)
{
var dbReport = dbContext.ReportsTbl.Where(w =>w.ID == reportId).Take(1);
return dbReport;
}
公共IEnumerable GetReport(int reportId)
{
var dbReport=dbContext.ReportsTbl.Where(w=>w.ID==reportId).Take(1);
返回dbReport;
}
这个例子将只返回一个报告,但它将被包装在一个可枚举的内部。您可以将其视为一个只包含一个报表的集合。如果在得到的空或空列表上使用First()方法,请尝试使用FirstOrDefault()方法exception@Jacek如果必须至少有一个,则可以使用
First()
。对空列表使用FirstOrDefault()
会抛出NullReference
异常