Question

I am trying to return the following query to a string array:

select top 10 c_initials, MAX(c_score) as MaxScore
from t_bisGame 
group by c_initials order by MaxScore desc

[WebMethod]
public string[] GetMyGameList()
{  
   //LINQ  
} 

I keep running into:

Cannot implicitly convert type 'AnonymousType#1[]' to 'string[]'

with the following code

var employees = from e in db.t_bisGames
                group e by e.c_Initials into egrp
                let max = egrp.Max(scor => scor.c_Score)
                select new
                {

                    Name = egrp.First(val => val.c_Score == max).c_Initials.ToArray(),
                    Score = egrp.First(val => val.c_Score == max).c_Score.ToString().ToArray()
                };
Était-ce utile?

La solution

The problem is that your query is returning 2 items, not just a string. Your LINQ is likely doing the same, and returning an anonymous type containing the initials and MaxScore as properties.

You can convert this to a string array via a second mapping operation (Select) at the end:

public string[] GetMyGameList()
{
     var query = db.BisGame.GroupBy(bg => bg.Initials)
              .Take(10)
              .Select(g => new { Initial = g.Key, MaxScore = g.Max(bg => bg.Score) });

     // Convert to string[] somehow, ie:
     return query.AsEnumerable().Select(i => string.Format("{0}:{1}", i.Initial, i.MaxScore)).ToArray();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top