我有两个非常接近的方法,并且想创建一个我可以调用以保持代码DRY的方法
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();
}
答案 0 :(得分:1)
由于BestHighScore
和NightlyHighScore
具有相同的类型,您应该可以:
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
的实际类型。
答案 1 :(得分: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)