Fredou
Fredou

Reputation: 20100

to do a substring using LINQ on a string, do I have to correct syntax?

    Dim myString As String = "1234567890"
    Dim Part As String = ""

    Part = myString.Substring(2, 2) '34
    Part = New String(myString.Skip(2).Take(2).ToArray) '34

This code work but the linq one take about 1300% more time than the substring.

I have 2 questions

  1. Do I have the correct syntax(for LINQ)?
  2. Should I stick with the string.substring?

Upvotes: 1

Views: 1993

Answers (2)

Simon P Stevens
Simon P Stevens

Reputation: 27499

1) Yes, that is one way of doing it. I'm sure there are others.
2) Yes. Definitely.

Linq takes longer because it is doing a lot more. It has to create an expression tree, evaluate the expression an iterator, which calls the strings enumerator to move along the string the required number of characters, then do it all again for your second method call, then convert the whole lot to an array, then create a new string and process the array into the new string.

All the substring call has to do is a bit of pointer arithmetic to extract the middle portion of the string and return the new string.

This is a perfect example of an absolutely terrible use for Linq. Linq is for helping the developer with complex queries on enumerable or query-able data, not processing strings. Here the overhead of Linq by far outweighs any benefits in readability. Stick with the substring call.

[Edit: Corrected linq details following comments from Marc]

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500145

You should definitely stick with Substring. It's tailor-made for this situation, and it doesn't require all the extra bits of LINQ.

Just because you can do something with LINQ doesn't mean it's necessarily a good idea. When the data type you're using has the exact operation you want defined on it already, using an extra layer of abstraction is somewhat pointless.

Upvotes: 4

Related Questions