Linq - How to take the result for a query in Linq and add it to an Array
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 stri开发者_如何转开发ng. 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;
}
If you want to have ContentId as a string, then do this:
var queryTitle = (from content in context.CmsContents
select new
{
Title = content.Title, // String
ContentId = content.ContentId.ToString() // Int
}).ToArray();
queryTitle will be an array of the anonymous type created, which has two properties:
- Title
- ContentId
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:
var queryTitles = (from content in context.CmsContents
select "Title: " + content.Title + ", ContentId: " + content.ContentId.ToString()).ToArray();
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
var resultArray = titlesAsArray
.Select(a => new[]
{
a.ContentId.ToString(), a.Title
})
.SelectMany(x => x).ToArray();
or to modifiy your original query
var resultArray = context.CmsContents.Select(content => new[]
{
content.ContentId.ToString(), content.Title
}).SelectMany(content => content).ToArray();
var strings = from content in context.CmsContents
select string.Format ("{0} {1}",
content.ContentId,
content.Title
);
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 call ToArray
extension method on the result.
精彩评论