1

I have a List which is returned to me from a 3rd party. Each string in the list ends in "mph" and I would like to remove the "mph". The obvious answer is to foreach over the list but I didn't know if there was a more efficient way to do it.

Thanks.

1
  • 3
    one way or other, you have to perform a iteration! Commented Feb 23, 2013 at 17:07

7 Answers 7

5

in a word, no. Something has to pass over the list in order to modify it. A for loop is probably the most efficient way though not necessarily the most concise

Sign up to request clarification or add additional context in comments.

Comments

4

You have to iterate over the list to touch each item and make a change.

The easiest way to do this is via linq:

  var originallist = new List<string> { "50mph", "35mph", "100mph" };
  var newlist = list.Select(s => s.Substring(0, s.Length - 3));

Comments

3

You can use LINQ instead of a foreach loop:

list.Select( s => s.Substring(0, s.Length - 3) )

5 Comments

-1 Wrong function ;P. ForEach doesn't exist and not close to what its called unfortunately. Ok i undid the -1
It certainly does exist: msdn.microsoft.com/en-us/library/bwabdf9z.aspx, but I was just thinking of the wrong function. Fixed.
I'm sorry. Wow I learned something new. Its kind of strange they have that in List but not in linq. It also bothered me there was a Find in list but the equivalent in linq is first which kind of messed me up. +1
Yes, if strings weren't immutable that might be more efficient for many types of operations. But see this article: blogs.msdn.com/b/ericlippert/archive/2009/05/18/…
@AndrewMao: IMHO, less code to write is also a kind of "efficiency" :)
1

you can use LINQ for that purpose. Something like this might works :

var noMph = theList.Select(p => p.Replace("mph", "").ToList();

2 Comments

Note that this isn't more "efficient" than a for loop. In fact, it's probably less efficient.
well, at least it is more efficient in terms of the amount of code you have to write :)
1

Simple Answer : You Can't


One way or another you have to perform a iteration.

it may be :

foreach
for
List.ForEach

Comments

1

Well you can write

mylist.Select(s=>s.Substring(0, s.Length-3));//Can add .ToList() here

But that is using a loop. You don't have to write the foreach at least :)

2 Comments

@AndrewMao: Hahahaha oh crap, fixed :). -edit- funny enough this always gets me in real code until i run and see the mistake on screen
Also fix the substring to Substring :)
1

this will work

List<string> newList = new List<string>();

mylist.ForEach((item)=>
  {
    item=item.Replace("mph",""); 
    newlist.Add(item);
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.