2010-01-04 18 views
7

噢,我只是發現錯誤是由另一部分代碼引起的。 案件關閉。使用Linq在組中選擇最大值

我有2個表

1- userinfo的

id uid name 
1 11 Billy 
2 22 Paul 
3 33 Joshua 

2-分數

id uid score 
1 11 30 
2 22 40 
3 11 50 
4 11 60 
5 33 20 
6 33 70 
7 33 80 

我有一個名爲ScoreUser

public class ScoreUser{ 
public long uid{get; set;} 
public string name{get;set;} 
public int score{get;set;} 
} 

我想使用類升inq查詢上述兩個表,獲取每個用戶的最高分數並將其映射到ScoreUser對象中。 我使用下面的代碼:

from s in Scores 
join i in UserInfos 
on s.uid equals i.uid 
group uscore by new { s.uid, i.name} into g 
let maxScore = g.Max(p => p.score) 
select new ScoreUser 
{ 
uid = g.Key.uid, 
name = g.Key.name, 
score = maxScore 
} 

然而,這個代碼並不起作用。它產生7個物體而不是3個。 我該怎麼辦?

+0

返回的是什麼?你有錯誤嗎? – Theresa 2010-01-04 13:40:47

+0

不應該切換Scores和UserInfos表嗎? 「從我在UserInfos加入分數...」基本上,現在你的主要選擇是7個記錄長。 – 2010-01-04 13:42:52

回答

9

當它應該是聚合器時,您也正在按score進行分組。試試這個:

from s in Scores 
join i in UserInfos on s.uid equals i.uid 
group by new { s.uid, i.name } into g 
select new ScoreUser 
{ 
    uid = g.Key.uid 
    name = g.Key.name, 
    score = g.Max(p => p.score) 
} 

(更新)

我看你發現了這個問題。不過,我離開你這裏測試此查詢:

class UserInfo 
    { 
     public int Id { get; set; } 
     public int UId { get; set; } 
     public string Name { get; set; } 
    } 

    class Score 
    { 
     public int Id { get; set; } 
     public int UId { get; set; } 
     public int SScore { get; set; } 
    } 

    public class ScoreUser 
    { 
     public int uid { get; set; } 
     public string name { get; set; } 
     public int score { get; set; } 

     public override string ToString() 
     { 
      return string.Format("UId:{0} Name:{1} Score:{2}", uid, name, score); 
     } 
    } 


    static void Main(string[] args) 
    { 

     List<UserInfo> infos = new List<UserInfo>() 
     { 
      new UserInfo {Id = 1, UId = 11, Name = "Billy"}, 
      new UserInfo {Id = 2, UId = 22, Name = "Paul"}, 
      new UserInfo {Id = 3, UId = 33, Name = "Joshua"} 
     }; 

     List<Score> scores = new List<Score>() 
     { 
      new Score {Id = 1, UId = 11, SScore = 30}, 
      new Score {Id = 2, UId = 22, SScore = 40}, 
      new Score {Id = 3, UId = 11, SScore = 50}, 
      new Score {Id = 4, UId = 11, SScore = 60}, 
      new Score {Id = 5, UId = 33, SScore = 20}, 
      new Score {Id = 6, UId = 33, SScore = 70}, 
      new Score {Id = 7, UId = 33, SScore = 80} 
     }; 

     var qry = from s in scores 
        join i in infos on s.UId equals i.UId 
        group s by new { s.UId, i.Name } into g 
        select new ScoreUser 
        { 
         uid = g.Key.UId, 
         name = g.Key.Name, 
         score = g.Max(p => p.SScore) 
        }; 

     foreach (var su in qry) 
     { 
      Console.WriteLine(su); 
     } 
    } 

打印:

UId:11 Name:Billy Score:60 
UId:22 Name:Paul Score:40 
UId:33 Name:Joshua Score:80