开发者

Linq return string array

开发者 https://www.devze.com 2023-04-03 14:55 出处:网络
/// <summary> /// Returns list of popular searches /// </summary> public static string[] getPopularSearches(int SectionID, int MaxToFetch)
/// <summary>
/// Returns list of popular searches
/// </summary>
public static string[] getPopularSearches(int SectionID, int MaxToFetch)
{
    using (MainContext db = new MainContext())
    {
        return (from c in db.tblSearches where c.SectionID == SectionID && c.Featured select new[] { c.Term });
    }
}

I looked at other questions but they seem to be slightly different, I get the error:

Cannot implicitly convert type 'System.Linq.IQueryable<string[]>' to 'string[]'

I know this is pro开发者_如何学运维bably simple, could someone point out what's wrong here please?


Sure - you're trying to return from a method declared to return a string[], but you're returning a query - which isn't a string in itself. The simplest way of converting a query to an array is to call the ToArray extension method.

However, as you're already selecting a string array for every element in the query, that would actually return string[][]. I suspect you really want to select a single string per query element, and then convert the whole thing into an array, i.e. code like this:

public static string[] GetPopularSearches(int sectionID, int maxToFetch)
{
    using (MainContext db = new MainContext())
    {
        var query = from c in db.tblSearches
                    where c.SectionID == sectionID && c.Featured
                    select c.Term;
        return query.Take(maxToFetch)
                    .ToArray();
    }
}

Note that:

  • I've renamed the method and parameters to match .NET naming conventions
  • I've added a call to Take in order to use the maxToFetch parameter


You are attempting to return an unmaterialized query. The query is only evaluated when it is enumerated. Luckily for you, the ToArray method take the pain out of enumerating and storing. Simply adding it to the end of your query should fix everything.

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select new[] { c.Term }
).ToArray();

EDIT

Looking in more detail, perhaps:

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select new[] { c.Term }
).SelectMany(x => x).ToArray();

to flatten the results of your query, or even (less redundantly):

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select c.Term
).ToArray();


Add .ToArray() at the end of the return statement.

0

精彩评论

暂无评论...
验证码 换一张
取 消