Getting sub string [closed] - c#

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"];

Related

Compare several strings in an if statement [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 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))
{
}

C# Sorting string list with underscore and hyphen [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a List<string> with values SK-Disbur and SK_Recon. When I sort the list, what should be the output?
I am getting:
SK_Recon
SK-Disbur
I was expecting the other way around with Disbur before Recon, since hyphen comes before underscore.
Here is my code:
List<string> list=new List<string>();
list.Add("SK-Disbur");
list.Add("SK_Recon");
list.Sort();
for(int i=0;i <list.Count;i ++)
{
Console.WriteLine(list[i]);
}
.NET doesn't use ASCII, it uses Unicode UTF-16. When you perform a string sort, By default .NET are using the current culture's rules for sorting. In this case, those rules indicate that "_" comes before "-". You can get the result you expect by using the "ordinal" string comparer:
List<string> list = new List<string>()
{
"SK-Disbur",
"SK_Recon",
"SK1",
"SK2"
};
list.Sort(StringComparer.Ordinal);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
you will get this result
SK-Disbur
SK1
SK2
SK_Recon
but if you use list.Sort() (by default) the result is very different
SK_Recon
SK-Disbur
SK1
SK2
By default list.Sort() uses the current culture's rules for sorting. That means each character is sorted using a linguistic sort (alphabetic sequence). You should use ordinal sorting so that its sorted by the binary value of each character. Try:
list.Sort(StringComparer.Ordinal);

How to convert 2 properties of every record in a List from string to int(by extracting numbers from string) C# [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 4 years ago.
Improve this question
Currently, I have a List of objects. Each record has three properties.
HEID = string type,(The string always looks like 12R,27L,36)
LEID = string type,(The string always looks like 12R,27L,36)(I want to
extract the numbers and set them as an int.)
RunwayId = int,
I want to take the HEId and LEId strings, and extract the numbers, and store it as a new List, or change the current properties to int type with converted values.
I am looping through the list, and this is where I want to convert each record's string type property to int type.
Thanks
yourList.Select(obj => new { HEID = float.Parse(obj.HEID), LEID = float.Parse(obj.LEID) });
this will return an IEnuramble of anonymous objects
you can also create new type with these properties as int and instead of selecting an anonymous type u can cast or select to the new type
yourList.Select(obj => new NewTypeWithInt { HEID = float.Parse(obj.HEID), LEID = float.Parse(obj.LEID) });
or even cleaner you can create a cast opreator
yourList.Select(obj => (NewTypeWithInt)obj);

Put a string into a linq expression? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to do a LINQ expression where the expression varies on how deep the expected node is in the hierarchy.
So I use concat on a string like this:
var parString = string.Concat(Enumerable.Repeat(".SelectMany(f => f.level)", level));
so if its 4 levels deep I get the string :
string1 = ".SelectMany(f => f.level).SelectMany(f => f.level).SelectMany(f => f.level).SelectMany(f => f.level)"
I then want to use this string in a LINQ expression, example:
List + string1 + .FirstOrDefault(.......);
Is this even possible? How can I do it?
Use a for loop to determine how many times to call .SelectMany:
var query = List;
for(int depth = 4; depth > 0; depth--)
{
query = query.SelectMany(f => f.level);
}
// Materialize query with `FirstOrDefault` or anything you need
Notice that currently if you reach the maximum depth and still continue you will get an exception. To solve that you can add an if statement to check that f.level is not null or not empty depending on your logic. Something like:
for(int depth = 4; depth > 0; depth--)
{
query = query.SelectMany(f => f.level ?? Enumerable.Empty<YourType>());
}

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.

Categories

Resources