Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 可数返回优先_C#_Linq - Fatal编程技术网

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