[英]How to fetch entries starting with the given string from a SQL Server database?
[英]How can I get 10 entries from a database, ordered by score, given a starting position, using Entity Framework?
我正在嘗試為游戲創建排行榜服務。 我有一個數據庫,用於存儲帶有 ID(PK)、用戶名(唯一)和分數的玩家。 我正在嘗試查詢這個數據庫,以便給定一個球員,我得到它和列表中接下來的 9 名球員(或者,如果沒有足夠的球員,最后 10 名球員,因為我想要的球員在那里得到保證)。 這是我獲取列表的代碼:
var asyncPlayers = await (context.Players
.OrderByDescending(p => p.Score)
.Skip(skip).Take(10))
.ToListAsync();
問題是我不知道如何確定“跳過”而不返回整個數據庫,訂購它並找到它是 position。 有什么辦法可以在不獲取整個數據庫的情況下做到這一點?
按照有關如何在 linq 中獲取索引的文檔,我們可以使用索引。
首先,在每種情況下或當前播放器中用於跳過和獲取的圖像,按點降序排列:
最后的代碼(未經測試,可能有一些打字錯誤):
var numberToGet = 3; // Nubmers of recors to get
var currentPlayerId = 34; // current player id or other field
// All players ordered by score descending
var allPlayersOrderByScore =
context.Players
.OrderByDescending(p => p.Score)
.Select((player, index) =>
new { player = player, index = index }
);
var allPlayersOrderByScoreCount =
allPlayersOrderByScore.Count();
// Get current player from previous list, by id or other field
var currentPlayer =
allPlayersOrderByScore
.FirstOrDefault(x=>x.player.PlayerId = currentPlayerId)
// Check if not null
if(currentPlayer!=null){
var currentPlayerIndex = currentPlayer.index;
if(allPlayersOrderByScoreCount-currentPlayerIndex >= numberToGet){
// GREEN, "normal case"
var list =
allPlayersOrderByScore
.Skip(currentPlayerIndex)
.Take(numberToGet)
}else{
// YELLOW, "anormal case"
var skip = allPlayersOrderByScoreCount-numberToGet;
var list =
allPlayersOrderByScore
.Skip(skip)
.Take(numberToGet)
}
}
不確定我是否理解正確,但如果我理解...
var player = _db.Players.GetbyName("john smith");
var topPlayers = _db.Players.OrderByDescending(x=>x.Score).skip(0).Take(9);
///NB check if already in list.
var payerPlusOtherScoreplayers = topPlaters.Add(player).OrderByDescending(x=>x.Score)
這行不通嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.