Sometimes you have the need to extract text out of a string, once extracted you need to get the right data into lists. Say one list of integers and one list of decimals. Using the extension methods now found in .Net one can easily do those operations.
Here is the data in a string, “12 34 56.1 18 19.25 41”. We want the integers separated out from the decimals into their own lists respectively as their native values (int/decimal) and not strings. Using Where, Select and a couple of Lambdas we can get to the intended result.
string data =@"12 34 56.1 18 19.25 41"; string dataAsStrings = data.Split( ' ' ); List<decimal> decs = ( dataAsStrings.Where( itm => itm.Contains( '.' ) ) ) .Select( itm => Decimal.Parse( itm ) ) .ToList(); List<int> ints = ( dataAsStrings.Where( itm => itm.Contains( '.' ) == false ) ).Select( itm => int.Parse( itm ) ).ToList(); foreach ( decimal dc in decs ) Console.WriteLine( dc ); /* Outputs 56.1 19.25 (on seperate lines)*/ foreach ( int it in ints) Console.WriteLine( it ); /* Outputs 12 34 18 41 (on seperate lines)*/
- Step one is top split the string using string.Split.
- Step 2 is take that split data and enumerate over it using the Where method.
- Within the Where we use a lambda which basically says for each item in the list, if it contains a period select it and return it. Note the result of most Extension methods is deemed a projection which is really a list of the values. Where, Select and ToList all return projections.
- Once the Where is done we call/chain the Select Extension. The select is saying take the projection from the Where and on each item parse out the value and return it in its native, non string format.
- Using the ToList on the projection created by the Select we take the items and specify it to be in a List<> format.
We didn’t have to do the ToList and could have said something like this:
var decs = ( dataAsStrings.Where( itm => itm.Contains( '.' ) ) ) .Select( itm => Decimal.Parse( itm ) ); foreach ( decimal dc in decs ) Console.WriteLine( dc ); /* Outputs 56.1 19.25 (on seperate lines)*/
Which would have been just as vaild. At runtime the var would have been internally known as IEnumerable<decimal> under the covers and as you can see that is just a different type of list and works just the same.