Linq - 如何在 Linq 中获取查询结果并将其添加到数组中
我使用 c#、linq 和 EF4 我想请求你的帮助。
我的问题: 我有一个 linq 查询,但我需要将该查询的结果插入到数组字符串中。 添加的值应该是 Title 和 ContentId(EF 中的 ContentId 是一个 INT,但我需要它作为字符串)
请让我知道,非常感谢!PS:请发布完整的代码:-)
public static string[] GetCompletionList(string prefixText, string count)
{
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
var queryTitle = (from content in context.CmsContents
select new
{
Title = content.Title, // String
ContentId = content.ContentId.ToString() // Int
}).ToArray();
return queryTitle;
}
I use c#, linq and EF4 I would like ask your help.
My question:
I have a linq query, but i need the result for this query be inserted in an array string.
Value added should be Title and ContentId (ContentId from EF is an INT but i need it as a string)
Please let me know, many thanks in advances!PS: Please post the full code :-)
public static string[] GetCompletionList(string prefixText, string count)
{
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
var queryTitle = (from content in context.CmsContents
select new
{
Title = content.Title, // String
ContentId = content.ContentId.ToString() // Int
}).ToArray();
return queryTitle;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望 ContentId 作为字符串,请执行以下操作:
queryTitle 将是创建的匿名类型的数组,它有两个属性:
均为字符串类型。
如果您不想拥有匿名类型的数组,而是想要一个字符串数组,请使用以下代码:
If you want to have ContentId as a string, then do this:
queryTitle will be an array of the anonymous type created, which has two properties:
Both of type string.
If you don't want to have an array of the anonymous type, but an array of strings, then use this code:
如果您希望在一大串字符串中包含 contentID 和 Title(从您的问题来看,听起来像这样,但不是很清楚),您可能想尝试此操作
或修改您的原始查询
if you are looking to have contentID and Title in one big array of string (from your question, it sounds like that but not very clear), you might want to try this
or to modifiy your original query
这应该对你有帮助。
请注意,一个常见的误解是您需要一个数组来处理查询结果 - 事实上,您不需要,结果已经是
IEnumerable
。如果您确定需要一个数组,只需将查询括在括号中,然后对结果调用ToArray
扩展方法。That should help you.
Note that it's a common misconception that you need an array to work with query results—in fact, you don't, the result is already
IEnumerable
. If you're sure that you need an array, just wrap query in parentheses and callToArray
extension method on the result.