Line array of Linq strings

/// <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 a bit different, I get an error:

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

I know this is probably simple, can someone point out what is wrong here?

+6
source share
3 answers

Of course, you are trying to return from the method declared to return string[] , but you are returning a query that is not the string itself. The easiest way to convert a query into an array is to call the ToArray method.

However, since you already select an array of strings for each query element, this actually returns string[][] . I suspect that you really want to select one row for each query element and then convert it all to 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 renamed the method and parameters according to the .NET naming conventions
  • I added a Take call to use the maxToFetch parameter
+15
source

You are trying to return a raw request. The request is evaluated only when it is listed. Luckily for you, the ToArray method relieves the pain of enumeration and storage. Just adding it at the end of your request, you have to fix it.

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

EDIT

Looking in more detail, it is possible:

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

to smooth out 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(); 
+4
source

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

0
source

Source: https://habr.com/ru/post/896977/


All Articles