Check if a string has a certain length and contains certain letters - c#

So I want to check that a string has all these attributes:
Five characters long, and
The first character is one of:
O, or
S, or
J, or
C, and
The last four characters are digits.
This is my code:
Console.Write("IDnumber : ");
IDnumber= Console.ReadLine();
IDnumberLength = IDnumber.Length;
if (MemberNumber.Length == 5 &&
char.IsLetter(IDnumber[0]) && <-- I know how to validate any letter but not certain letter
char.IsDigit(IDnumber[1]) &&
char.IsDigit(IDnumber[2]) &&
char.IsDigit(IDnumber[3]) &&
char.IsDigit(IDnumber[4]))

You could use Regex like this:
var regex = new Regex("^[OSJC][0-9]{4}$");
Console.WriteLine(regex.IsMatch("J1234"));
Console.WriteLine(regex.IsMatch("J124"));
Console.WriteLine(regex.IsMatch("X1234"));
That would give you:
True
False
False
In your code you could use it like this:
Console.Write("IDnumber : ");
IDnumber = Console.ReadLine();
if (Regex.IsMatch(IDnumber, "^[OSJC][0-9]{4}$"))
{
// Success
}
else
{
// Failed
}

Without using a regular-expressions:
Boolean isValid =
value.Length == 5 &&
( value[0] == 'O' || value[0] == 'S' || value[0] == 'J' || value[0] == 'C' ) &&
Char.IsDigit( value[1] ) &&
Char.IsDigit( value[2] ) &&
Char.IsDigit( value[3] ) &&
Char.IsDigit( value[4] );

Related

To convert if condition to linq in cshtml

Code
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
}
}
I have tried the following code and unable to complete it fully as expected
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where((a => a.CurrentStatus == 1 || a.CurrentStatus == 2)
&& )
})
How to convert the above if condition to linq in cshtml. Thanks
the else-if relationship is an OR relationship. So simply combine the two lines. the inner nested if inside the else if is an AND relationship. This would go into the second set of parentheses
Collection = Model.Collection.Where
(
(a => a.CurrentStatus == 1 || a.CurrentStatus == 2) ||
((a.CurrentStatus == 3 || a.CurrentStatus == 4) && a.Date != null && a.Date <= 30)
)
EDIT:
Here is another suggestion: extract the readable code into an own method that evaluates the condition and returns the boolean result. This way you can make a predicate that can be accepted by the Where method:
private bool IsForDisplay( ModelDataType Model )
{
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
return true;
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
return true;
}
}
return false;
}
now you can use it simply in the linq expression:
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where(a => IsForDisplay(a))
});

how to make textbox numbers and operators only and in a valid form . . .

when I am entering input like this "12312.-.-.,," program is not working or giving any error
string c = textBox1.Text;
if (c.Contains(".") || c.Contains("-") || c.Contains("1") || c.Contains("2") || c.Contains("3") || c.Contains("4") || c.Contains("5") || c.Contains("6") || c.Contains("7") || c.Contains("8") || c.Contains("9") || c.Contains("0"))
{
if (c.IndexOf('-') == 0 || c.IndexOf('.')==c.Length-1)
{
c = c.Substring(1, c.Length - 1);
if (c.Contains("-") || c.Contains("."))
{
MessageBox.Show("Error");
}
}
}
else { textBox1.Clear(); }```
You really should check input values with regular expressions:
Regex rgx = new Regex(#"^-?\d+(\.\d+)?$");
string test1 = "-123.23";
string test2 = "12312.-.-.,,";
if (!rgx.IsMatch(test1)) MessageBox.Show("Error in test1");
if (!rgx.IsMatch(test2)) MessageBox.Show("Error in test2");
The code doesnt enter your check for string to "not" start with '0' or end with '.' i assume?
if (!(c.IndexOf('-') == 0 || c.IndexOf('.')==c.Length-1))

Store math operator in variable

I am creating an application in C# MVVM. I have a simple question. Is there any possibility to store math operator in variable? I have a code like that:
public ICollectionView FilteredCollection
{
get
{
return filteredCollection;
}
set
{
filteredCollection = value;
OnPropertyChanged("FilteredCollection");
}
}
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary == Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
);
What I want to achieve:
In fourth line (DynamicSearchEmployeeSalary) math operator should be depended on following conditions:
if (IsPressedEqual == true)
VARIABLE = "=="
if (IsPressedLess == true)
VARIABLE = "<"
if (IsPressedGreater == true)
VARIABLE = ">"
if (IsPressedLess == true && IsPressedEqual == true)
VARIABLE = "<="
if (IsPressedGreater == true && IsPressedEqual == true)
VARIABLE = ">="
Scenario:
For example I put a value like 10000 in textbox, then click on button with "=" operator. As a result I want to receive Employees with Salary equals than 10000.
Then I click on ">". And I have Employees with Salary greater and equals 10000.
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary VARIABLE Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
I've made a simple Rule Based Engine ... I think it will help you in your issue ...
please find it as a nuget package here: https://www.nuget.org/packages/IbnSherien.RuleBasedEngine/
you can create a rule like this:
var rule = RuleEngine.CreateRule<Employee>()
.If<Employee>(e => e.EmployeeSalary).GreaterThan(DynamicSearchEmployeeSalary)
.Validate();
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || rule.Match((Employee)x).IsMatch)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
feel free to add any comments or contribute to the package

Modify IList Query Statement

I have the following statement, and I want to modify it to not select all tables.
Exclude 2 columns customerItemNo and manufacturerItemNo in the if, and
Exclude 2 columns customerItemNoAppend and manufacturerItemNoAppend in the else if.
How can I do it?
if (p.UserInternal == 'Y' && p.UserActive == 'Y')
inventorySummary = DataProvider.SelectCondition<Q_TBL_INVENTORY_SUMMARY>
(r => r.InventoryLocationNo == location);
else if (p.UserInternal != 'Y' && p.UserActive == 'Y')
inventorySummary = DataProvider.SelectCondition<Q_TBL_INVENTORY_SUMMARY>
(r => r.InventoryLocationNo == location && (r.CustomerID == customerID || r.CustomerID == " "));
else
inventorySummary = new List<Q_TBL_INVENTORY_SUMMARY>();

if statement, boolean value

This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:
// the new IsDecimal method
public bool IsDecimal(TextBox textBox, string name)
{
//make sure the string only contains numbers and numeric formatting
string s = textBox.Text;
int decimalCount = 0;
bool validDecimal = true;
foreach (char c in s)
{
if (!(
c == '0' || c == '1' || c == '2' || // numeric chars
c == '3' || c == '4' || c == '5' ||
c == '6' || c == '7' || c == '8' ||
c == '9' || c == '.' ||
c == '$' || c == '%' || c == ',' || // formatting chars
c == ' '
))
{
validDecimal = false;
break;
}
if (c == '.')
{
decimalCount++;
}
} // end loop
if (validDecimal && decimalCount <= 1)
{
return true;
}
else
{
MessageBox.Show(name + " must be a decimal number.",
"Entry Error");
textBox.Focus();
return false;
}
}
My question is about this if statement and boolean value:
if (validDecimal && decimalCount <= 1)
{
return true;
}
I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.
A bool value on its own is the same as value == true
If you have
bool trueThing = true;
then the following are all equivalent (and true)
trueThing;
trueThing == true;
(trueThing == true) == true;
((trueThing == true) == true) == true;
and so on. The simplest, least verbose form is the first: trueThing. It's not a 0 or 1, it's a true or false.
Operator Precedence. This:
if (validDecimal && decimalCount <= 1)
is interpreted as:
if (validDecimal && (decimalCount <= 1))
not
if ((validDecimal && decimalCount) <= 1)
In other words, the <= happens before the &&.
I think you're reading the statement wrong, if you placed parentheses, so that it's obvious what's going on, it would look like
(validDecimal) && (decimalCount <= 1)
not
(validDecimal && decimalCount) <= 1
In English: check that validDecimal is true and decimalCount is at most 1. The comparison against true is implicit, because it's not necessary.
In C#, variable of type bool can have one of two values, true or false, but they don't act as numbers, so you can't say they are 1 and 0 (although they are usually implemented that way).
Also, in most languages, if you mean “a and b are both at most x”, you can't write it as a && b <= x. That's just not how (most) computer languages work.
You can write
if (validDecimal == true && decimalCount <= 1)
but it is equivalent to the shorthand way
if (validDecimal && decimalCount <= 1)
When the type is a bool no need to again use
== true
as it is assumed
I don't really know in c#, but in Java, you can even do this:
boolean b = 1<2;
1<2 is true (remember, it's a boolean equation), so the value assigned to b is true. Everything you put in the if, is interpreted as
if(whateverLogicEquationHereIsTrue){do this}
else{means that the boolean input to the if, has come to be false}
now, what is the output of this?
if(!(1>2)){print "a"}
else{print "b"}
hint: ! is the logical operator NOT

Categories