Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq return string array

/// <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 probably simple, could someone point out what's wrong here please?

like image 218
Tom Gullen Avatar asked Sep 09 '11 12:09

Tom Gullen


1 Answers

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
like image 50
Jon Skeet Avatar answered Sep 28 '22 02:09

Jon Skeet