如何使用max和group by将tsql转换为linq并返回String []

时间:2014-05-06 21:27:59

标签: c# linq tsql asmx sql-to-linq-conversion

我正在尝试将以下查询返回到字符串数组:

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  
} 

我一直在遇到:

  

无法隐式转换类型' AnonymousType#1 []'到' string []'

使用以下代码

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()
                };

1 个答案:

答案 0 :(得分:2)

问题是您的查询返回2个项目,而不仅仅是字符串。您的LINQ可能也是这样做的,并返回包含首字母和MaxScore作为属性的匿名类型。

您可以通过最后的第二个映射操作(Select)将其转换为字符串数组:

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();
}