get values from string
in my variable:
string selectedObjects;
i have one long value like:
"123;132;213;231;"
i want to get 4 times values as: "123;" , "132;" , "213;" and "231;".
i tryed with foreach as:
public ActionResult ShowHistory(string selectedObjects)
{
foreach (string item in selectedObjects)
{开发者_如何转开发
item = selectedObjects.Split(';');
}
but it doesnt work. how can i do that?
The flow is incorrect. Split returnes an array through which you should than iterate, using foreach if that's your choice. So:
foreach (string item in selectedObjects.Split(';'))
{
// do whatever you want with the items
}
You can use a regular expression:
foreach (Match m in Regex.Matches("123;132;213;231;", @"\d+;"))
string value = m.Value; //Do something worthwhile with the value.
All of the other answers are wrong or overkill - unless I'm missing something.
public ActionResult ShowHistory(string selectedObjects)
{
foreach (string tempItem in selectedObjects.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries))
{
string item = tempItem + ";"; // Add back on the ; character
}
// .. do something
The RemoveEmptyEntries is required, otherwise, you'll get an empty string at the end (because your input string ends with ";"). Also, string.Split does not preserve the separator char, so you need to add it back in if you want it (hence the tempItem
).
Split returns an array of string
.
string selectedObjects = ...;
foreach (string item in selectedObjects.Split(';'))
{
// do work
}
foreach(string item in selectedObjects.Split(new [] {';'},
StringSplitOptions.RemoveEmptyEntries)
.Select( x=> x+";"))
{
//process item
}
Split method returns array of string, try somehting like this
string selectedObjects = "123;132;213;231;";
string[] s = selectedObjects.Split(';');
foreach (string item in s )
{
Console.Writeline(item.ToString());
}
You need to append the semi-colon again after splitting.
public ActionResult ShowHistory(string selectedObjects)
{
var items = selectedObjects.Split(';')
.Where(i => !string.IsNullOrEmpty(i))
.Select(i => i + ";");
...
}
Or (if you can guarantee that exact format)
public ActionResult ShowHistory(string selectedObjects)
{
var items = selectedObjects.TrimEnd(';')
.Split(';')
.Select(i => i + ";");
...
}
精彩评论