[英]Find all occurences of a value in a list
我正在嘗試獲取 player.userID 在列表中顯示的次數,但我似乎無法弄清楚如何,我已經在互聯網上搜索了一個小時。
class ConfigData
{
[JsonProperty(PropertyName = "Ban")]
public uint ban = 3;
[JsonProperty(PropertyName = "Kick")]
public uint kick = 2;
[JsonProperty(PropertyName = "Banned Message")]
public string kickMessage = "You are banned";
}
class StoredData
{
public List<ulong> Reports = new List<ulong>();
public List<ulong> Banned = new List<ulong>();
public List<ulong> Kicked = new List<ulong>();
}
void OnPlayerConnected(BasePlayer player)
{
if (storedData.Reports.Count(player.userID) == configData.ban)
{
storedData.Banned.Add(player.userID);
}
if (!storedData.Banned.Contains(player.userID))
{
Network.Net.sv.Kick(player.net.connection, rust.QuoteSafe(configData.kickMessage));
}
else
{
return;
}
}
如果需要,我可以發布完整的代碼。
Count
方法接受一個 lambda 告訴它計數的條件。
由於您的報告只是用戶 ID 的列表,您需要做的就是:
int count = storedData.Reports.Count(reportedID => reportedID == player.userID);
if (count >= configData.ban) // NOTE: changed this to >=
{
...
}
作為旁注,如果它是一個對象列表,並且您想與名為someProperty
的屬性進行比較,那么它將是:
report => report.someProperty == player.userID
。
lambda 只是 function 的簡寫; =>
之前的部分是參數列表(這里,它只接受一個參數 - storedData.Reports
的當前元素)。 參數名稱是任意的(您的選擇)。
=>
后面的部分是 function 主體,帶有隱式返回,所以
reportedID == player.userID
就像{ return reportedID == player.userID; }
{ return reportedID == player.userID; }
。
Count
方法基本上遍歷Reports
中的 ID,對於每個 ID,它都會詢問 lambda 是否應該計算它,方法是將 ID 傳遞給 lambda,並檢查 Z945F3ZFC 是否返回 449518A466CZ 是否為true
或false
。
PS在你的代碼中它說:
if (!storedData.Banned.Contains(player.userID)) { /* kick */ }
確定要踢掉不在封禁名單中的玩家嗎? 檢查與踢/禁止相關的邏輯(也許做一些測試),這對我來說看起來不太正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.