[英]Linq - How to take the result for a query in Linq and add it to an Array
我使用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;
}
如果要使用ContentId作為字符串,請執行以下操作:
var queryTitle = (from content in context.CmsContents
select new
{
Title = content.Title, // String
ContentId = content.ContentId.ToString() // Int
}).ToArray();
queryTitle將是創建的匿名類型的數組,該數組具有兩個屬性:
兩者均為字符串類型。
如果您不想有一個匿名類型的數組,而是一個字符串數組,請使用以下代碼:
var queryTitles = (from content in context.CmsContents
select "Title: " + content.Title + ", ContentId: " + content.ContentId.ToString()).ToArray();
如果您希望在一大串字符串中包含contentID和Title(從您的問題來看,聽起來像是這樣,但不是很清楚),您可能想嘗試一下
var resultArray = titlesAsArray
.Select(a => new[]
{
a.ContentId.ToString(), a.Title
})
.SelectMany(x => x).ToArray();
或修改您的原始查詢
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
);
那應該對你有幫助。
請注意,這是一個常見的誤解,您需要一個數組來處理查詢結果-實際上,您不需要,結果已經是IEnumerable
。 如果確定需要一個數組,只需將查詢括在括號中並在結果上調用ToArray
擴展方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.