Compare two strings and check the changed value in a contain range - c#

I have 6 properties:
oldprop1,oldprop2,oldprop3
newprop1,newprop2,newprop3
I am going to check if the value changed. If it changed in a certain combination of ways, then I want to log it.
If these 5 changes happen, then it should be logged:
P to Y
P to N
blank to Y -- here blank means ""
blank to N
N to Y
What I am doing now
if (!oldprop1.Trim().Equals(newprop1.Trim()) && (oldprop1.ContainsAny("P", "N","")) && newprop1.ContainsAny("Y", "N"))
{
//log me to DB
}
if (!oldprop2.Trim().Equals(newprop2.Trim()) && (oldprop2.ContainsAny("P", "N", "")) && newprop2.ContainsAny("Y", "N"))
{
//log me to DB
}
if (!oldprop3.Trim().Equals(newprop3.Trim()) && (oldprop3.ContainsAny("P", "N", "")) && newprop3.ContainsAny("Y", "N"))
{
//log me to DB
}
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (string needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
Is there any better way to write this?

better to use switch statement .here is the code
public void CompareAndLog(string first, string second)
{
switch (first)
{
case "P": if (second == "Y" || second == "N") ;//log me to db
break;
case "N": if (second == "Y") ; //log me to db
break;
case "": if (second == "Y" || second == "N") ;//log me to db
break;
}
}

You can write a method where you pass in oldpropX and newpropX and do the logic in there, then you just do:
if (SomeFunc(oldprop1, newprop1) || SomeFunc(oldprop2, newprop2)...)
{
// log to DB.
}
SomeFunc() would do the Equals check and the P,N,etc. check.

Related

How can I adjust that when I write: paper and the bot then writes: scissors, it says either "win" or "lose"

Im new in c# & thats one of my first games, so sorry for that maybe bad written code.
Note: Please dont leak the full solution of that game. Just the solution of that situation. I wanna resolve it from myself. (Sry for my bad english)
{
string[] list = { "Scissors", "Paper", "Rock" };
Random rnd = new Random();
int index = rnd.Next(list.Length);
Console.WriteLine("Do you wanna play Scissors, Paper, Rock? Type 'y' for Yes and 'n' for No");
string output = Convert.ToString(Console.ReadLine());
if (output == "y")
{
Console.WriteLine("Scissors, Paper or Rock?");
string abfrage = Convert.ToString(Console.ReadLine());
if (abfrage == "Scissor" || abfrage == "Paper" || abfrage == "Rock")
{
Console.WriteLine(list[index]);
string convert = Convert.ToString(list[index]);
if (convert == abfrage)
{
Console.WriteLine("Draw");
}
if (convert != abfrage) // Here is the problem
{
Console.WriteLine("Win");
}
}
}
You need to check the actual winning condition, not just the equality
if (convert == abfrage) {
Console.WriteLine("Draw");
return;
}
if (abfrage == "Scissor") {
if (convert == "Paper") {
Console.WriteLine("Win");
} else if (convert == "Rock") {
Console.WriteLine("Lose");
}
}
// repeat for other cases

Filter data from datatable for one of columns in asp.net

I have a datatable which fetches some records. So there is one column name as UPDATED_STATUS. In that column either Pre Hoto or Post Hoto value will come.
So what I want is, Either any one of those values should be their in that column then only the it should move ahead otherwise it should prompt alert as
Either Pre Hoto or Post Hoto can be their
Below is sample image for reference
Below is the code for getting the datatable with the UPDATED_STATUS column
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
Your current check (if (dtStatus == null && dtStatus.Rows.Count < 0)) is wrong:
when dtStatus is null, you continue checking dtStatus.Rows, which throws a nullref exception (you just found out that it was null);
Rows.Count is never less than zero.
Try if (dtStatus == null || dtStatus.Rows.Count == 0) to check whether there is no status at all (it is null) or no status rows (count is zero). The || will prevent checking for dtStatus.Rows when it was found that dtStatus is null.
&& means that both sides must be true at the same time.
|| means that at least of the sides must be true (both true is also fine).
Both don't evaluate the second test when the first already decided the outcome (false && whatever is always false, true || whatever is always true)
Are you looking for like this !
foreach (DataRow row in dtStatus.Rows)
{
if (string.IsNullOrEmpty(Convert.ToString(row["UPDATED_STATUS"])) ||
(Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "pre hoto" &&
Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "post hoto"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
break;
}
else { }
}
I have got a way to get this done.. Here I go
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
}
DataTable dtGetHotoPre = null;
var rows = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "PRE HOTO");
if (rows.Any())
{
dtGetHotoPre = rows.CopyToDataTable();
}
DataTable dtGetHotoPost = null;
var rowsPost = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "POST HOTO");
if (rowsPost.Any())
{
dtGetHotoPost = rowsPost.CopyToDataTable();
}
string strFlagStatus = "";
if (dtGetHotoPre != null)
{
if (dtGetHotoPost != null)
{
strFlagStatus = "No Process";
}
else
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPost;
}
}
else
{
if (dtGetHotoPost != null)
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPre;
}
else
{
strFlagStatus = "No Process";
}
}
// if(dtGetHotoPre != null && dtGetHotoPost != null)
if (strFlagStatus == "No Process")
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('The sites contains both Pre and Post Hoto Status, so it cannot be uploaded');", true);
}
else
{
// will move ahead.
grdDvHoto.DataBind();
}

Efficient way for multiple 2 value true false if statement

I have an if else statements that has 2 values that need to be evaluated whether they're null or not, then based on that, it chooses the right statement. The code below:
int? x;
int? y;
if(x == null and y == null) { do this part; }
else if (x != null and y == null) {do this second part; }
else if (x == null and y != null) {do this third part; }
else { do this last part; }
I am trying to find if there is a more efficient way to implement this. There is the option of a case statement, but I still want to know if there is a better way.
I'd use a nested if, so each variable is only evaluated once, instead of multiple times as suggested in the OP snippet.
if (x == null) {
if (y == null) {
// Both are null
} else {
// Only x is null
}
} else {
if (y == null) {
// Only y is null
} else {
// Neither are null
}
}

Can't get the correct Bool result in C#

I have a form where I would like to check for validation before processing the form. My form has 2 sections so I want to make sure that at least one item from each section is selected when they press submit button, and if they did then go to Dashboard.aspx. Even if I put all the required info when it checks for result1 and result2, I get false. Result1 and Result2 won't get the correct value. Even if the values are True again it passes false.
Here is my code:
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
bool result1 = false;
bool result2 = false;
CheckWireFromValidation(result1);
CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation (bool result1)
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
result1 = true;
}
else
{
result1 = false;
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
}
return result1;
}
public bool CheckWireToValidation(bool result2)
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
result2 = true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
}
return result2;
}
You're not using the results of CheckWireToValidation. You're using the false value you allocate initially.
Try this
bool result1 = false;
bool result2 = false;
if (CheckWireFromValidation(result1) && CheckWireToValidation(result2))
{
Response.Redirect("~/DashBoard.aspx");
}
Edit
The behavior you're expecting is that of the out parameter modifier. But please don't write code that way ...
I edited your code to get rid of .. em .. cruft. This should be more readable.
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
if (CheckWireFromValidation() && CheckWireToValidation())
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation ()
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
return false;
}
}
public bool CheckWireToValidation ()
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
return false;
}
}
Since you are passing Result1 and Result2 in as parameters instead assigning them. The results will never be set.
Here's one correct way of doing this
bool result1 = CheckWireFromValidation(result1);
bool result2 = CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
and also a side note. I think we can safely remove the boolean parameter from the CheckWireFromValidation methods. Since the return value doesn't depends on the input variable.
Hope this helps.

How can I loop and check for correct user input in C#?

In this following main method I am trying to code so if the user does not input the proper response, then the code will loop until the user does provide the correct response.
I know I'm off center here, but I'm drawing a blank of how to correct this.
Please keep in mind I'm tying to keep this simple and basic.
public static void Main()
{
string name = "";
float startBal = 0;
int acctNum = 0;
string userInput = "";
float[] deposits = new float[30];
float[] withdrawls = new float[30];
DisplayIntroduction();
name = GetName();
startBal = GetStartBal();
acctNum = CreateAccount();
Console.WriteLine("\n{0}, here is your new account # {1}\n", name, acctNum);
do
{
Console.Write("Enter a 'D' to Deposit, 'W' to Withdrawl, or 'X' to End the program: ");
userInput = Convert.ToString(Console.ReadLine());
if (userInput.ToUpper() == "D")
{
//do the deposit, modify the deposit array
Console.WriteLine("You entered D");
}
else if (userInput.ToUpper() == "W")
{
//do the withdrawl, modify the withdrawl array
Console.WriteLine("You entered W");
}
else if (userInput.ToUpper() == "X")
{
//end the program, clear screen and display the summary
Console.WriteLine("You entered X");
}
else
{
Console.WriteLine("Please enter a valid option:");
}
} while (userInput.ToUpper != "D" || userInput.ToUpper != "W" || userInput.ToUpper != "X");
}
Common mistake, it should be some AND operators in your while, not OR.
while (userInput.ToUpper != "D" && userInput.ToUpper != "W" && userInput.ToUpper != "X")
You want to loop if it's different than D AND different than W. Else it will always be true, since it cannot be D and W at the same time.
For example, if user inputs D, you get false true true, but you need a global result of false to leave the loop. With ANDs, you get a global result of false, while with OR you get true.
You can also use make it a little bit more compact (and less error-prone) with some LINQ (Works great for a lot of elements):
while(!new[] {"D", "W", "X"}.Contains(userInput));
It is not efficient to check twice a thing, you are checking user input in if-statements and again in the while-condition.
The simplest way is to set up a bool type variable to indicate whether user has entered the correct response or not.
bool flag = false;
do{
//your code
}
while(!flag)
and add this in every if-statement:
flag = true;
indicating that the user has inputed the correct value.
Pierre-Luc Pineault is correct.. But more logically it would be best to do..
while(!(userInput.ToUpper == "D" || userInput.ToUpper == "W" || userInput.ToUpper == "X"))
The "while" condition means the loop will keep triggering until the statement is false.
(userInput.ToUpper != "D" || userInput.ToUpper != "W" || userInput.ToUpper != "X");
Is going to be looping forever.
If the user enters "D" for instance
false OR true OR true
true
You'll want an & instead
(userInput.ToUpper != "D" && userInput.ToUpper != "W" && userInput.ToUpper != "X");
If user enters a "D"
false AND true AND true
= false
(break out)
If user enters a "Z"
true and true and true
= true (remain in loop)
My version is something like this:
// While loop usually read better: keep on asking again and again until
// valid value is chosen
while (true) {
Console.Write("Enter a 'D' to Deposit, 'W' to Withdrawl, or 'X' to End the program: ");
String userInput = Console.ReadLine(); // <- You don't need any Convert here
// Try not use ".ToUpper" - move it to comparison: StringComparison.OrdinalIgnoreCase
if (String.Equals(userInput, "D", StringComparison.OrdinalIgnoreCase)) {
Console.Write("You've entered 'D'");
break;
}
else if (String.Equals(userInput, "W", StringComparison.OrdinalIgnoreCase)) {
Console.Write("You've entered 'W'");
break;
}
else if (String.Equals(userInput, "X", StringComparison.OrdinalIgnoreCase)) {
Console.Write("You've entered 'X'");
break;
}
Console.WriteLine();
Console.WriteLine("You've written an invalid option.");
}

Categories