BirnBaumBlüte BirnBaumBlüte - 2 months ago 6x Question

Linq Substring by Index

I got a List containing Integer values and a String. For example

DetermineDigits = {1,8,16,24}
String = "|Field1, Field2; Field26"

I want to get following output:

Dim output as List(Of String) = Feld1

I tried

For i = 1 To DetermineDigits.Count - 1
Dim NoOfDigits As Integer = DetermineDigits(i) - DetermineDigits(i - 1) - 1
tmpStr = String.Substring(DetermineDigits(i - 1), NoOfDigits)

which works, but I'd rather use Linq. Any ideas?


You may use Enumerable.Range() combined with Select() to iterate through DetermineDigits indexes:

Dim DetermineDigits = {1, 8, 16}
Dim Str = "|Field1, Field2; Field26"
Dim pos = DetermineDigits.Concat(New Integer() {Str.Length}).ToArray()

Dim output = Enumerable.Range(1, pos.Count() - 1) _
    .Select(Function(i) Str.Substring(pos(i - 1), pos(i) - pos(i - 1)))

Mind the pos array which is the DetermineDigits with last substring end position added to it. Without this addition you're rather missing the last substring.

Alternatively you may consider using Zip() to get a list of {StartPos, EndPos} indexes for each of your substring.

That being said I suggest considering to use regex to extract your substrings. Those in your example can be easily grabbed with simple \w+ so you'll end up with quite compact code:

Dim Str = "|Field1, Field2; Field26"
Dim output = Regex.Matches(Str, "\w+").Cast(Of Match)().Select(Function(m) m.Value).ToList()

NB: don't forget to add Imports System.Text.RegularExpressions.

If your substring pattern is more complex, we may further elaborate the regex.