我正在将此 C# 与 linq to sql 一起使用:
string currentLabel = from s2f in stream2FieldTypesTable
where s2f.s2fID == item.s2fID
&& (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)
select s2f.s2fLabel;
我收到一个编译器错误,提示我无法分配类型 System.Linq.IQueryable<string>
至 string
.
我试过这段代码:
string currentLabel = from s2f in stream2FieldTypesTable
where s2f.s2fID == item.s2fID
&& (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)
select s2f.s2fLabel.ToString();
这会返回相同的错误。我相信这是一件简单的事情。我错过了什么?我只想要第一个 s2fLabel
匹配 where 子句。
最佳答案
您查询的实际类型将是IEnumerable。 LINQ 有一个概念 deffered execution ,为了让你的查询实际执行,你需要调用一个方法来遍历 IEnumerable:
string currentLabel = (from s2f in stream2FieldTypesTable
where s2f.s2fID == item.s2fID
&& (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)
select s2f.s2fLabel)
.FirstOrDefault();
要获得精确的实例,它可以是 FirstOrDefault() 方法或 SignleOrDefault() 或只是 First() 或 Single ()。唯一的区别是没有“OrDefault()”的方法在枚举不能满足他们的期望时会抛出异常,而带有“OrDefault()”的方法只会返回 null。
编辑
Single 和 First 之间的区别是 Single 期望集合中有exact one 元素,首先需要至少一个元素。
关于c# - 如何使用linq to sql从行中选择一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479692/