Reputation: 383
I have a list of strings like this:
List<string> list = new List<string>();
list.Add("Item 1: #item1#");
list.Add("Item 2: #item2#");
list.Add("Item 3: #item3#");
How can I get and add the substrings #item1#, #item2# etc into a new list?
I am only able to get the complete string if it contains a "#" by doing this:
foreach (var item in list)
{
if(item.Contains("#"))
{
//Add item to new list
}
}
Upvotes: 8
Views: 49241
Reputation: 18106
The code will solve your problem.
But if the string does not contain #item#
then the original string will be used.
var inputList = new List<string>
{
"Item 1: #item1#",
"Item 2: #item2#",
"Item 3: #item3#",
"Item 4: item4"
};
var outputList = inputList
.Select(item =>
{
int startPos = item.IndexOf('#');
if (startPos < 0)
return item;
int endPos = item.IndexOf('#', startPos + 1);
if (endPos < 0)
return item;
return item.Substring(startPos, endPos - startPos + 1);
})
.ToList();
Upvotes: 1
Reputation:
LINQ would do the job nicely:
var newList = list.Select(s => '#' + s.Split('#')[1] + '#').ToList();
Or if you prefer query expressions:
var newList = (from s in list
select '#' + s.Split('#')[1] + '#').ToList();
Alternatively, you can use regular expressions as suggested with Botz3000 and combine those with LINQ:
var newList = new List(
from match in list.Select(s => Regex.Match(s, "#[^#]+#"))
where match.Success
select match.Captures[0].Value
);
Upvotes: 2
Reputation: 3952
Here's another way using a regex with LINQ. (Not sure your exact requirements reference the regex, so now you may have two problems.)
var list = new List<string> ()
{
"Item 1: #item1#",
"Item 2: #item2#",
"Item 3: #item3#",
"Item 4: #item4#",
"Item 5: #item5#",
};
var pattern = @"#[A-za-z0-9]*#";
list.Select (x => Regex.Match (x, pattern))
.Where (x => x.Success)
.Select (x => x.Value)
.ToList ()
.ForEach (Console.WriteLine);
Output:
#item1#
#item2#
#item3#
#item4#
#item5#
Upvotes: 3
Reputation: 39610
You could have a look at Regex.Match
. If you know a little bit about regular expressions (in your case it would be a quite simple pattern: "#[^#]+#"
), you can use it to extract all items starting and ending with '#'
with any number of other characters other than '#'
in between.
Example:
Match match = Regex.Match("Item 3: #item3#", "#[^#]+#");
if (match.Success) {
Console.WriteLine(match.Captures[0].Value); // Will output "#item3#"
}
Upvotes: 15
Reputation: 563
try this.
var itemList = new List<string>();
foreach(var text in list){
string item = text.Split(':')[1];
itemList.Add(item);
}
Upvotes: 0
Reputation: 389
You could do that by simply using:
List<string> list2 = new List<string>();
list.ForEach(x => list2.Add(x.Substring(x.IndexOf("#"), x.Length - x.IndexOf("#"))));
Upvotes: 0
Reputation: 4837
How about this:
List<string> substring_list = new List<string>();
foreach (string item in list)
{
int first = item.IndexOf("#");
int second = item.IndexOf("#", first);
substring_list.Add(item.Substring(first, second - first);
}
Upvotes: 0