Following code is supposed generate a new ID (PID) for a new client based on the client name's first letter and the existing IDs in the range which are stored in a database.
For ex lets say if the new client's name is "Abc" and if last ID in the database starting from letter A, is A200. Then the new ID should be A201.
This code compiles and runs giving the desired out put but I hope this could be optimized further.
Expecting your suggestions on improving this...
private void GeneratePIDforNewPoint(string pointName)
{
string firstLetterOfPointName; // variable to hold first letter of "point name" being passed to this method
string lastExistingPID; // variable to hold the last PID (most recent hence largest) from the list of PIDs retrieved from the database
int lastDigitOfExistingPID; // variable to hold last digit of the "lastPID" (ex- digit '2' from PID 'F002')
string finalPID; // variable to hold out put (the generated new PID for the new point)...
firstLetterOfPointName = pointName[0]; // Get the fist letter of the point name...
List<string> pidList=_ds.GetPIDs(firstLetterOfPointName); // Calling method to get the pid list from database
if (pidList.Count >=1) // At the end of this if block, numeric part of the new PID will be desided
{
pidList.Sort();
lastExistingPID = pidList[pidList.Count - 1];
lastDigitOfExistingPID = int.Parse(lastExistingPID[lastExistingPID.Length - 1].ToString());
}
else
{
lastDigitOfExistingPID = 0;
}
lastDigitOfExistingPID += 1;
// Found digit will be converted to the pid format by attaching the starting letter and zeros to make the length.(format --> A001/ B099 / C100 etc.)
finalPID= firstLetterOfPointName + String.Format("{0:000}", lastDigitOfExistingPID );
_view.PID = finalPID;
}
public List<string> GetPIDs(string firstLetterOfPointName)
{
string selectStatement = @"SELECT PID FROM point WHERE PID like @PID";
List<string> pidList = new List<string>(); // List to store all retrived PIDs from the database...
// Retrieve all existing PIDs starting with "letter" from the database
using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
{
sqlCommand.Parameters.Add("@PID", SqlDbType.VarChar).Value = firstLetterOfPointName + '%';
sqlConnection.Open();
using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
{
// If reader has data, are added to the list
while (dataReader.Read())
{
pidList.Add(dataReader.GetString(0).Trim());
}
return pidList;
}
}
}
}
create table charid { id char, count long }
. Search forpointName[0]
asid
in the table, incrementcount
and write it back while locking the row. IfpointName[0]
is not in the table, add it and set thecount
to 1 while locking the table. \$\endgroup\$