Abe
Abe

Reputation: 1929

How to get a Substring from a string in C# where the string has sequential numbers?

I have a Name, Value pair both strings stored in a dictionary.

e.g.,

Name        |   Value   |
-------------------------
Dim1L9      |   10.98   |
-------------------------
Dim14L10    |   26.32   |
-------------------------   
Dim14L11    |   95.25   |
-------------------------
Dim1L10     |   9.99    |

From this table i would like to get the sum of Dim1 10.98 + 9.99 = 20.97. How can i do this?

Upvotes: 1

Views: 59

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Just in case you want to get sum for all names:

var regex = new Regex(@"^[a-zA-Z]+(\d+)L\d+$");
var sumByDimension = from kvp in dictionary
            let match = regex.Match(kvp.Key)
            where match.Success
            group kvp by match.Groups[1].Value into g
            select new
            {
                Dimension = g.Key,
                Sum = g.Sum(kvp => kvp.Value)
            };

Output:

{ Dimension: "1", Sum: 20.97 }
{ Dimension: "14", Sum: 121.57}

Upvotes: 1

Related Questions