Compare several strings in an if statement [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
Is there a better way to do this?
var line = sr.ReadLine();
string[] values = line.Split(';');
if (d == "abc"|| d == "def"|| d == "ghi")
{
}
Since I seemed to get an error message regarding this if statement I added && false to every comparison and replaced the == with the equals method, both without positive results, but this turned out irrelevant.

I can recommend this
notice that if d is null no exception is throw
And also you can extend your list for other compare strings if necessary
You do not need to write a large if statement with comparing d for each string
string d = values[10];
var list = new List<string>() { "abc", "def", "ghi" };
if (!list.Contains(d))
{
}

Related

c# When the textbox text is null or empty error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to when textbox1.text null or empty error happened, return to 0
In short, you should always validate user input with the TryParse style methods.
You should never never *N̨͈̤̣͊͊́̃E̡͎̺̺̭̒̍̂̐̓V̢̱̓͒Ẻ̫͉̙̈́̽Ŕ̨͉̹̦͑̌̑́͟ use Convert methods.
So, you could do something like this...
var r = byte.TryParse(textBox1.Text, out var tempR) ? tempR : 0;
var g = byte.TryParse(textBox2.Text, out var tempG) ? tempG : 0;
var b = byte.TryParse(textBox3.Text, out var tempB) ? tempB : 0;

How to insert a string in alphabetical order to a new array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I've been looking up a lot of videos, tried using the bubble sort method, insert sort method, but nothing seems to work for this particular problem. I am supposed to add a string (movie name) to an array, but I must do it alphabetically. I can not sort the array after it's completed, it must be done while I add the new strings.
I've seen a lot posts with similar questions like this but all of them sort the array after its completed!
Here is a couple of methods that might help you.
private void PrintAlphabetically()
{
string[] movies = new string[5];
movies[0] = "b";
movies[1] = "x";
movies[2] = "m";
movies[3] = "a";
movies[4] = "t";
AddToStringArray(ref movies, "s");
Array.Sort(movies, (x, y) => String.Compare(x , y));
for (int i = 0; i < movies.Length; i++)
{
Console.WriteLine(movies[i]);
}
}
private void AddToStringArray(ref string[] array, string item)
{
List<string> list = array.OfType<string>().ToList();
list.Add(item);
array = list.ToArray();
}

C# indexof is entering if statement when it should not based on the List i have [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
So this should be super simple , perhaps indexOf is not the way to go
var incoming = "MDd"; // incoming data
List<string> cities = new List<string>();
cities.Add("MD");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
if(cities.IndexOf(incoming) != 1 )
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}
I am seeing "found" with linqpad output , whether it is correct "MD" or "MDd" why? and what do I change to fix this?
From the documentation of IndexOf:
Return Value The zero-based index position of value if that string is
found, or -1 if it is not. If value is String.Empty, the return value
is 0.
When value is not found in the string, it returns -1, otherwise it returns index position, which is greater than or equal to 0. So either check if index is not -1 or check if it >= 0. I personally prefer the latter one:
// if (cities.IndexOf(incoming) != -1)
if (cities.IndexOf(incoming) >= 0)
{
Console.WriteLine("found");
}
This is a typo error. You want to check for -1 rather than 1 in your if statement:
if(cities.IndexOf(incoming) != -1)
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}

richtextbox application test c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm very new to c#. I created a forms. A richtextbox and a button in it.
I have a list of operators: Sum, Subtract,Multi,Div.I want to run a small richtextbox test. For example,in the richtextbox I write a text (eg. Sum(1,2)) and then click the button. A return result(eg.3) prints in the richtextbox.
My idea is to use string contains
foreach( var element in operatorlist)
{
string text=richtextbox.text;
if( text.contains(element)== true)
{
element(parameter1,parameter2);//something like this
}
}
I met two questions right row.
My first question is how to get the mathematical operation from the richtextbox text. Is there a better way than mine?
My second question is once we know the operator,how to allocate the two parameters in the richtextbox to the operator.
I'm not asking for coding, I'm just looking for ideas. If you have a good idea and wish to share.
You can evaluate an expression using the DataTable.Compute function:
int p1 = 1 ; string s1 = p1.ToString() ;
int p2 = 2 ; string s2 = p2.ToString() ;
int p3 = 3 ; string s3 = p3.ToString() ;
// Compute (p1+p2)*p3 ==> 9
int result = new DataTable().Compute( "("+s1+"+"+s2+")*"+s3+")","") ;
or directly:
string expression = "(1+2)*3" ;
int result = new DataTable().Compute(expression,"") ;
I think this comes down to personal style. Your way will definitely work, so good on you for that. The way I would do it is to create a Dictionary of strings to an enum. So for example, said dictionary and enum might look like this:
enum Operator { Addition = 0, Subtraction = 1, Multiplication = 2, Division = 3, etc};
var operatorDictionary = new Dictionary<string, Operator>()
{
{"Addition", Operator.Addition},
{"Subtraction", Operator.Subtraction},
etc...
};
Then to get the value you would just do
Operator operation;
operatorDictionary.TryGetValue(string operationString, out operation);
and you would have to then build some code that switches through the Operators and performs the correct operation. There is even a way of converting a string to an enum, so that would work as well.
It looks like the parameters are in a consistent format, so you would just make a simple method that splits by parenthesis and the comma, and returns the strings that it found.
Let me know if you need anything explained more.

Getting sub string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The question is on C#.
I have a string "value1=1234;value2=2345;value3=3456;value4= ..."
What is the best way to retrieve the values?
I thought about String.Split(";") but I don't know how to retrieve the values only. The result I get includes the prefix I don't want.
I only want the values of "1234", "2345", "3456"... nothing else, and them put them into a list of strings.
How do I solve this? Thanks.
If the format is always fixed, you can do it fairly easily via LINQ:
List<string> values = theString.Split(';').Select(s => s.Split('=')[1]).ToList();
Note that you may want to use RemoveEmptyEntries if your input string ends in a semi-colon:
List<string> values = theString
.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=')[1]).ToList();
This would prevent an exception from occuring within the Select. If the input doesn't end in a semi-colon, however, this wouldn't be necessary.
var text = "value1=1234;value2=2345;value3=3456;value4= ...";
var pieces = text.Split('=');
var values = new Dictionary<string,string>();
for(int index = 0; index < pieces.Length; index += 2)
{
values.Add(pieces[index], pieces[index + 1]);
}
This will give you a dictionary of the pairs where the key is the left-hand side of the '=' and the value is the string representation of the value, which allows your to do:
var value1 = values["value1"];
var value2 = values["value2"];

Categories

Resources