0

我有两种非常接近的方法,并且想要创建一种可以调用以保持代码干燥的方法

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

2 回答 2

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

于 2012-10-17T19:16:53.403 回答
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)
于 2012-10-17T19:17:29.143 回答