开发者

manipulate elements in a list - c#

I have a list of strings of the following pattern: "name\middleName". What is the nicest way to turn into a list in which all the el开发者_Go百科ements are just "name"? (i.e split the string and leave only the "name" part)

Thanks, Li


List<string> originalList = ...
List<string> newList = originalList.Select(s => s.Split('\\')[0]).ToList()


List<string> original = ...
List<string> nameOnly = original.ConvertAll(s => s.Substring(0, s.IndexOf('\\')));

If it's possible that there might not be a \ character in some elements of the original list then you'll need an additional check to avoid exceptions:

List<string> nameOnly = original.ConvertAll(s => {
                                                     int i = s.IndexOf('\\');
                                                     return (i == -1) 
                                                         ? s
                                                         : s.Substring(0, i);
                                                 });


//your list of strings in format (name\middleName)
List<string> list;
List<string> newList;

foreach(string item in list)
   newList.Add(item.Substring(0, item.IndexOf("\\")));

That would make a copy of your string list into a new one formatted like you wanted.


Tokenize "/" and assign the first string to name variable. Or just make loop of all those strings in a list and inside a loop do a loop on a string length which puts chars into variable and exits when reaches "/" and then stores it as a name.


Here's a regular expression solution for you that doesn't create a new list.

for(int i = 0; i < list.count; i++)
{
     list[i] = Regex.Match(List[i],@"^\w+").value      
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜