C# LINQ:从 IQueryable<> 中的单个列中选择数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/699418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ: Select data from a single column in IQueryable<>
提问by Paul Stevens
I have a table that I need to extract data from, and wish to discard one of the two columns that the data comes from. In my DB, I have "ObjectID (PK)" and "ObjectName".
我有一个需要从中提取数据的表,并希望丢弃数据来自的两列之一。在我的数据库中,我有“ObjectID (PK)”和“ObjectName”。
I wish to use this data to populate a SelectList in an ASP.NET MVC project, and so have an IQueryable object in my code which looks as follows:
我希望使用此数据填充 ASP.NET MVC 项目中的 SelectList,因此在我的代码中有一个 IQueryable 对象,如下所示:
public IQueryable<objectRef> FindSomeObject()
{
return from myObj in db.TableName
orderby myObj.colName
select myObj;
}
If I attempt to change the last line to pull only a single column worth of data, such as:
如果我尝试更改最后一行以仅提取一列数据,例如:
select new { myObject.colName };
I get a warning that I am attempting to implicitly convert an anonymous type to my current type.
我收到一条警告,提示我试图将匿名类型隐式转换为当前类型。
The annoyance is that this query gets used in ViewData[""]
to set a SelectList
, which displays the drop down fine, but writes the PK value to the new table instead of the text.
令人烦恼的是,此查询用于ViewData[""]
设置 a SelectList
,它可以很好地显示下拉列表,但将 PK 值而不是文本写入新表。
I'm assuming that I know so little about this that I cannot even ask Google the right question, as hours of RTFM have revealed nothing useful. Any help would be appreciated.
我假设我对此知之甚少,以至于我什至无法向 Google 提出正确的问题,因为数小时的 RTFM 没有发现任何有用的信息。任何帮助,将不胜感激。
采纳答案by Jon Skeet
You need to change the return type of your method - if you only want to select one column, just declare that you're going to return something of that column. For example:
您需要更改方法的返回类型 - 如果您只想选择一列,只需声明您将返回该列的某些内容。例如:
public IQueryable<string> FindSomeObject()
{
return from myObj in db.TableName
orderby myObj.colName
select myObj.colName;
}
That basically says it's a query which returns a sequence of strings - which is what you want, I assume.
这基本上说它是一个返回字符串序列的查询 - 我假设这就是你想要的。
回答by eglasius
Use the type of colName, like:
使用 colName 的类型,例如:
public IQueryable<string> FindSomeObject()
{
return from myObj in db.TableName
orderby myObj.colName
select myObj.colName;
}
回答by Daniel Earwicker
Did you try:
你试过了吗:
public IQueryable<objectRef> FindSomeObject()
{
return from myObj in db.TableName
orderby myObj.colName
select myObj.colName;
}
And by the way, do you have a class called objectRef, starting lowercase? That ought to have an uppercase letter at the start (and it needs to be whatever type colName
is).
顺便说一句,你有一个名为 objectRef 的类,以小写开头吗?那应该在开头有一个大写字母(并且它需要是任何类型colName
)。