How to create string [] in LINQ query via Regex.Split ()

I am analyzing a comma delimited dataset using LINQ. In the LINQ query, I call Regex.Split several times to parse comma-separated elements. I am trying to figure out how I can avoid calling the .Split () method several times, but cannot figure it out.

Example:

// Sample data string data = @"A,1,Foo1,14:03:08,14/11/11, A,2,Foo2,11:51:11,09/11/11, A,3,Foo3,11:51:11, 09/11/11, A,4,Foo4,12:11:13,09/11/11, A,5,Foo5,12:23:02,13/11/11, A,6,Foo6,15:37:58,11/11/11"; // Add each line of data into an array string[] dataSplit = Regex.Split(data,"\r\n"); // Create an anon object for each line item var rows = from a in dataSplit select new { Name = Regex.Split(a, ",")[0], ID = Regex.Split(a, ",")[1], Val = Regex.Split(a, ",")[2], Time = Regex.Split(a, ",")[3], Date = Regex.Split(a, ",")[4] }; 

Note that in the LINQ query, I call Regex.Split to determine the index value for each position. Intuitively, it seems to me that calling .Split () for each anon prop is unnecessary overhead.

How to create a variable in a LINQ query that splits a string in a scope, so when I set the property of the anon object, I don’t need to call the Regex.Split () method?

+4
source share
2 answers

You can use the let clause to call only once:

 var rows = from a in dataSplit let splitValues = Regex.Split(a, ",") select new { Name = splitValues[0], ID = splitValues[1], Val = splitValues[2], Time = splitValues[3], Date = splitValues[4] }; 

As a side note - if you just split based on a specific character or string and not an expression, you should just use String.Split :

 string[] dataSplit = data.Split(new[] {Environment.NewLine}, StringSplitOptions.None); var rows = from a in dataSplit let splitValues = a.Split(",") select new { Name = splitValues[0], ID = splitValues[1], Val = splitValues[2], Time = splitValues[3], Date = splitValues[4] }; 
+1
source

You can save the subexpression in a variable with a let clause.

 var rows = from a in dataSplit let splitResult = Regex.Split(a, ",") select new { Name = splitResult [0], ID = splitResult [1], Description = splitResult [2], Time = splitResult [3], Date = splitResult [4] }; 
+4
source

Source: https://habr.com/ru/post/1381958/


All Articles