简体   繁体   中英

Find all occurences of a value in a list

I am trying to get the number of how many times player.userID shows in a list but I can't seem to figure out how, I have searched the internet for an hour now.

        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;
            }
        }

I can post the full code if needed.

The Count method accepts a lambda that tells it the condition on which to count.

Since your reports are just a list of user IDs, all you need to do is:

int count = storedData.Reports.Count(reportedID => reportedID == player.userID); 
if (count >= configData.ban)   // NOTE: changed this to >=
{
  ...
}

As a side note, if it was a list of objects instead, and you wanted to compare to a property named someProperty , then it would be:
report => report.someProperty == player.userID .

A lambda is just a shorthand for a function; the part before the => is the parameter list (here, it just accepts a single parameter - the current element of storedData.Reports ). The parameter name is arbitrary (your choice).

The part behind the => is the function body, with implicit return, so
reportedID == player.userID is like
{ return reportedID == player.userID; } { return reportedID == player.userID; } .

The Count method basically walks through the IDs in Reports , and for each one, it asks the lambda if it should count it or not, by passing that ID to the lambda, and checking if the lambda returns true or false .

PS In your code it says:

if (!storedData.Banned.Contains(player.userID)) { /* kick */ }

Are you sure you want to kick the players that are not in the banned list? Check the logic that relates to kicking/banning (maybe do some tests), it doesn't look quite right to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM