无法理解LINQ返回值

时间:2009-09-25 17:51:45

标签: c# linq linq-to-sql

我试图在此查询中返回实际值,但我只获得表达式。有人可以指出我正确的方向。

    public static String NurseName(Guid? userID)
    {
        var nurseName = from demographic in context.tblDemographics
                        where demographic.UserID == userID
                        select new {FullName = demographic.FirstName +" " + demographic.LastName};

        String nurseFullName = nurseName.ToString();

        return nurseFullName;
    }

nurseFullName 最终为 - > SELECT ([t0].[FirstName] + @p1) + [t0].[LastName] AS [FullName] FROM [dbo].[tblDemographics] AS [t0] WHERE ([t0].[UserID]) = @p0

3 个答案:

答案 0 :(得分:3)

试试这个:

var nurseName = (from demographic in context.tblDemographics
                where demographic.UserID == userID
                select new {FullName = demographic.FirstName +" " + demographic.LastName}).First().FullName;

您的代码抓取了一个集合,但不是特定的项目。此修改采用列表中的第一项并返回FullName属性。

答案 1 :(得分:3)

public static String NurseName(Guid? userID)
    {
        var nurseName = from demographic in context.tblDemographics
                        where demographic.UserID == userID
                        select demographic.FirstName +" " + demographic.LastName;

        return nurseName.SingleOrDefault();
    }

在上面的中,nurseName具有IQueryable表达式,因此它没有执行任何操作。当你枚举它时,它会调用查询。调用SingleOrDefault等方法时也是如此。


如果您要使用原始查询表达式,则可以:

public static String NurseName(Guid? userID)
    {
        var query= from demographic in context.tblDemographics
                        where demographic.UserID == userID
                        select new {FullName = demographic.FirstName +" " + demographic.LastName; }
        var nurseName = query.SingleOrDefault();
        return nurseName != null ? nurseName.FullName : "";
    }

Single与SingleOrDefault之间的区别在于后者允许空结果。 First与Single之间的区别在于后者阻止超过1行。

答案 2 :(得分:1)

public static String NurseName(Guid? userID)
{
    var nurseName = (from demographic in context.tblDemographics
                    where demographic.UserID == userID
                    select new {FullName = demographic.FirstName +" " + demographic.LastName}).SingleOrDefault();

    if(null == nurseName)
    {
        //TODO: Uh-Oh ID not found...
    }

    string nurseFullName = nurseName.FullName;

    return nurseFullName;
}