Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 462
Aamir Avatar asked Nov 30 '25 17:11

Aamir


2 Answers

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];
like image 52
Peter Lillevold Avatar answered Dec 03 '25 06:12

Peter Lillevold


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.

like image 26
Cheng Chen Avatar answered Dec 03 '25 07:12

Cheng Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!