Aamir
Aamir

Reputation: 15556

How to Split a string with LINQ and get the specified token

I have a tab-delimited string in the following format:

string line = "D\t892270\t88418\t6\t2452927\t-99999\t-99999\t12";

What I want is to get the value of the token specified through indexToGet.

I have written following LINQ query to do this which I am sure can be improved a lot but at the moment I am unable to do so. Can somebody improve this LINQ query for me?

int indexToGet = 7;
var val =
    (from str in line.Split('\t')
    select str).ToArray().GetValue(indexToGet).ToString();

Upvotes: 3

Views: 5055

Answers (2)

Peter Lillevold
Peter Lillevold

Reputation: 33920

Why do you need to use LINQ? The following code solves it without the LINQ overhead:

var val = line.Split('\t')[indexToGet];

Clarification: with the query comprehension syntax you've used there is no way of specifying that you only want an element at a given position. Thus, with LINQ, you will have to rely on the ElementAt extension method. So the first iteration of reduction you could replace .ToArray().GetValue(indexToGet).ToString(); and get this:

var val =
    (from str in line.Split('\t')
    select str).ElementAt(indexToGet);

Further, since there is no value in the query part other than being fancy (AND making the code harder to read), you could reduce to this:

var val = line.Split('\t').ElementAt(indexToGet);

And next, since ElementAt in this case is indexing into an array, it will be faster to just use the indexer directly:

var val = line.Split('\t')[indexToGet];

Upvotes: 6

Cheng Chen
Cheng Chen

Reputation: 43523

Don't force yourself to use LINQ. Why do you use

(from str in line.Split('\t') select str).ToArray()

instead of

line.Split('\t')

Another place to improve is that don't visit the elements using index directly without checking. You'd better check first to avoid the out of range exception.

And the last, what you get is a string, it's no necessary to call .ToString() again.

Upvotes: 2

Related Questions