2012-10-17 100 views
0

我有兩個方法,這是非常密切的,並希望創建一個方法,我可以打電話讓我的代碼幹創建具有LINQ方法

public IEnumerable<HighScoreViewModel> GetNightlyHighScores() 
{ 
    lock (_Key) 
    { 
     //return GetHighScores(x => x.NightlyHighScore); 

     return _allPlayers 
      .OrderByDescending(x => x.NightlyHighScore) 
      .Take(8) 
      .Select(x=> new HighScoreViewModel 
      { 
       Points = x.NightlyHighScore, 
       PointsText = "FG: " + x.NightlyHighScore, 
       ImageUrl = x.Facebook.SmallImageUrl, 
       DisplayName = x.DisplayName, 
      }).ToList(); 
    } 
} 

public IEnumerable<HighScoreViewModel> GetBestHighScores() 
{ 
    lock (_Key) 
    { 
     //return GetHighScores(x => x.BestHighScore); 

     return _allPlayers 
      .OrderByDescending(x => x.BestHighScore) 
      .Take(8) 
      .Select(x => new HighScoreViewModel 
      { 
       Points = x.BestHighScore, 
       PointsText = "FG: " + x.BestHighScore, 
       ImageUrl = x.Facebook.SmallImageUrl, 
       DisplayName = x.DisplayName, 
      }).ToList(); 
    } 
} 

我親近的兩個類似方法抽象的東西,但想不通的位標有「魔力」

public IEnumerable<HighScoreViewModel> GetHighScores<TKey>(Func<Player, TKey> highscore) 
{ 
    return _allPlayers 
     .OrderByDescending(highscore) 
     .Take(8) 
     .Select(x => new HighScoreViewModel 
     { 
      // Magic? 
      //Points = x.BestHighScore, 
      PointsText = "FG: " + x.BestHighScore, 
      //ImageUrl = x.Facebook.SmallImageUrl, 
      DisplayName = x.DisplayName, 
     }).ToList(); 
} 

回答

1

由於BestHighScoreNightlyHighScore具有相同的類型,你應該能夠做到:

public IEnumerable<HighScoreViewModel> GetHighScores(Func<Player, double> highscore) 
{ 
    return _allPlayers 
     .OrderByDescending(highscore) 
     .Take(8) 
     .Select(x => new HighScoreViewModel 
     { 
      // Magic? 
      Points = highScore(x), 
      PointsText = "FG: " + x.BestHighScore, 
      //ImageUrl = x.Facebook.SmallImageUrl, 
      DisplayName = x.DisplayName, 
     }).ToList(); 
} 

highscore應返回Points的實際類型。

+0

完美,謝謝!我會在兩分鐘內完成它標記 –

1

沒有那麼神奇,只是使用功能,從玩家獲取的價值:

public IEnumerable<HighScoreViewModel> GetHighScores<TKey>(Func<Player, TKey> highscore) 
{ 
    return _allPlayers 
    .OrderByDescending(highscore) 
    .Take(8) 
    .Select(x => new HighScoreViewModel 
    { 
     Points = highscore(x), 
     PointsText = "FG: " + highscore(x), 
     ImageUrl = x.Facebook.SmallImageUrl, 
     DisplayName = x.DisplayName, 
    }).ToList(); 
} 

調用具有:

GetHighScores(x => x.NightlyHighScore) 

GetHighScores(x => x.BestHighScore) 
+0

我不認爲這會編譯 - 沒有從'TKey'轉換爲'Points'類型。 – Lee

+0

它很接近,但TKey部分沒有使用它。 –