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 + ";");
...
}
Related
My code is as follows:
public List<string> connect(String query_physician, String query_institution)
{
Regex pattern = new Regex(#"(?<=""link""\:\s"")[^""]*(?="")");
MatchCollection linkMatches = pattern.Matches(customSearchResult);
var list = new List<string>();
list = linkMatches.Cast<Match>().Select(match => match.Value).ToList(); //put the links into a list?!
foreach (var item in list) //take each item (link) out of the list...
{
return item; // ...and return it?! //Error, because item is a string
}
return null;
}
Like you see, I want to return each link (as a readable list of my json result and display it in my RichTextBox, but I know, var item is a string. Otherwise it doesn´t work. Either I become an unreadable list, or a string (with string.Join(.....Cast<>()).
Do I have this right, string.Join(.....Cast<>()) adds the single strings together? Still, I don't want them together. Anyway, do you know a way to solve this problem?
By the way, return null is only a wildcard.
As I understand it is continuation of your previous question. Assuming you have this function (I simplified it a bit):
public List<string> connect(String query_physician, String query_institution)
{
...
return Regex.Matches(customSearchResult, #"(?<=""link""\:\s"")[^""]*(?="")")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
}
You can do the following:
List<string> list = connect("", "");
string linksFormatted = string.Join(",", list);
To show the content in RichTextBox:
richTextBox1.AppendText(string.Join(Environment.NewLine, list));
Look at your method signature return type is List of string no string,
so much simplest approach:
public List<string> connect(String query_physician, String query_institution)
{ ...
//restults container
List<string> resultContainer = new List<String>();
Regex pattern = new Regex(#"(?<=""link""\:\s"")[^""]*(?="")");
MatchCollection linkMatches = pattern.Matches(customSearchResult);
var list = new List<string>();
list = linkMatches.Cast<Match>().Select(match => match.Value).ToList(); //put the links into a list?!
foreach (var item in list) //take each item (link) out of the list...
{
//add item to list
resultContainer.Add(item);
}
return resultContainer;
}
I've a collection list.
List<string> mycollections = new List<string>(new string[]
{
"MyImages/Temp/bus.jpg",
"MyImages/Temp/car.jpg",
"MyImages/Temp/truck.jpg",
"MyImages/Temp/plane.jpg",
"MyImages/Temp/ship.jpg",
});
I required only files in a List such asbus.jpg, car.jpg...... Here i do not need "MyImages/Temp/" portion of the string in the same list.
I tried with Substring and Split with Linq queries but couldn't get the expected result.
Use Path.GetFileName instead of substring like:
var fileNames = mycollections.Select(r => Path.GetFileName(r)).ToList();
For output:
var fileNames = mycollections.Select(r => Path.GetFileName(r));
foreach (var item in fileNames)
{
Console.WriteLine(item);
}
Output:
bus.jpg
car.jpg
truck.jpg
plane.jpg
ship.jpg
How about this:
mycollections.Select(s => s.Split('/').Last());
That will split each string by slashes and return the last item.
So I have been asked to remove tour codes that end with the letter G, GE, G=, or Z. The only bad thing is I believe we use this call for a lot of pages and that is the reason I cant alter the database call in the first place so I want to do this specifically for this one person. My code is calling an arrayList that fills with all the tourcodes we have. Is there any way I can remove the tours with the letters above. Here is what I got to work with.
public void LoadTourCodes()
{
ddlTourCode.Items.Clear();
if (ddlTourCode.Visible)
{
ddlTourCode.Items.Add(new ListItem(" ", ""));
ArrayList tourCodes;
tourCodes = EblTipTours.FindTourCodes();
foreach (string tourCode in tourCodes)
{
ddlTourCode.Items.Add(tourCode);
}
}
}
You can do it using LINQ, like this:
var toRemove = new []{"G", "GE", "G=", "Z"};
foreach (string tourCode in tourCodes.Where(code => !toRemove.Any(suffix => code.EndsWith(suffix)))) {
ddlTourCode.Items.Add(tourCode);
}
If you cannot use LINQ because it's a legacy system, you can rewrite the code like this:
string[] toRemove = new string[] {"G", "GE", "G=", "Z"};
foreach (string tourCode in tourCodes) {
bool good = true;
foreach (string suffix in toRemove) {
if (tourCode.EndsWith(suffix)) {
good = false;
break;
}
}
if (!good) continue;
ddlTourCode.Items.Add(tourCode);
}
I have 3 strings, i would like find matches
http://www.vkeong.com/2011/food-drink/heng-bak-kut-teh-delights-taman-kepong/#comments
http://www.vkeong.com/2009/food-drink/sen-kee-duck-satay-taman-desa-jaya-kepong/
http://www.vkeong.com/2008/food-drink/nasi-lemak-wai-sik-kai-kepong-baru/
for each link above=="nasi-lemak"
{
found!
}
If you're just looking to see if a longer string contains a specific shorter string, use String.Contains.
For your example:
string[] urlStrings = new string[]
{
#"http://www.vkeong.com/2011/food-drink/heng-bak-kut-teh-delights-taman-kepong/#comments"
#"http://www.vkeong.com/2009/food-drink/sen-kee-duck-satay-taman-desa-jaya-kepong"
#"http://www.vkeong.com/2008/food-drink/nasi-lemak-wai-sik-kai-kepong-baru/"
}
foreach(String url in urlStrings)
{
if(url.Contains("nasi-lemak"))
{
//Your code to handle a match here.
}
}
You want the String.IndexOf method.
foreach(string url in url_list)
{
if(url.IndexOf("nasi-lemak") != -1)
{
// Found!
}
}
Surely we also need a LINQ answer :)
var matches = urlStrings.Where(s => s.Contains("nasi-lemak"));
// or if you prefer query form. This is really the same as above
var matches2 = from url in urlStrings
where url.Contains("nasi-lemak")
select url;
// Now you can use matches or matches2 in a foreach loop
foreach (var matchingUrl in matches)
DoStuff(matchingUrl);
Yep... it's one of those days.
public string TagsInput { get; set; }
//further down
var tagList = TagsInput.Split(Resources.GlobalResources.TagSeparator.ToCharArray()).ToList();
tagList.ForEach(tag => tag.Trim()); //trim each list item for spaces
tagList.ForEach(tag => tag.Replace(" ", "_")); //replace remaining inner word spacings with _
Both ForEach loops don't work. tagList is just a List.
Thank you!
Trim() and Replace() don't modify the string they're called on. They create a new string that has had the action applied to it.
You want to use Select, not ForEach.
tagList = tagList.Select(t => t.Trim()).Select(t => t.Replace(" ", "_")).ToList();
ForEach (and other "linq" methods) does not modify the list instance.
tagList = tagList.Select(tag => tag.Trim().Replace(" ", "_")).ToList();
The reason is string is immutuable. So the result of each Trim() or Replac() function will produce a new string. You need to reassign to the original element in order to see the updated value.
This is exactly why Microsoft havent implemented ForEach on an IEnumerable. What's wrong with this?
public string[] TagsInput { get; set; }
//further down
var adjustedTags = new List<string>();
foreach (var tag in TagsInput.Split(Resources.GlobalResources.TagSeparator.ToCharArray()))
{
adjustedTags.Add(tag.Trim().Replace(" ", "_"));
}
TagsInput = adjustedTags.ToArray();
If by don't work, you mean that they don't actually do anything, I think you need to adjust your code a bit:
public string TagsInput { get; set; }
//further down
var tagList = TagsInput.Split(Resources.GlobalResources.TagSeparator.ToCharArray()).ToList();
tagList.ForEach(tag => tag = tag.Trim()); //trim each list item for spaces
tagList.ForEach(tag => tag = tag.Replace(" ", "_")); //replace remaining inner word spacings with _
Trim and Replace don't change the value of the string, they return the new string value.