0

I have a file : site.log

19 www.mysite.org 
300 cod.mysite.org 
100 www.newfile.com
199 py.mysite.org
45 python.mysite.org/als
45 mysite.org/als/4/d

I would like to go through all the poems containing the string mysite.org and get the number from the beginning of the text and sum all numbers in front of the given text

File.ReadLines(filePath).Where(x => x.Contains("mysite.org")).SelectMany(...));
ImpoUserC
  • 599
  • 5
  • 16

2 Answers2

2

You are close. After the Where use Select to project only the beginning of the line:

var result = File.ReadLines(filePath)
                 .Where(x => x.Contains("mysite.org"))
                 .Select(x => int.Parse(x.Split()[0]))
                 .Sum();

Notice that the parsing to int might fail of the prefix is not an integer. You can use TryParse instead. If you will want so you can have a look here: https://stackoverflow.com/a/46150189/6400526

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
0

I Split by a space and TryParse first value, if success, I take this value, if not, I take 0

var result = File.ReadLines("")
                 .Where(x => x.Contains("mysite.org"))
                 .Select(x => {int temp; return int.TryParse(x.Split(' ')[0], out temp) ? temp : 0;})
                 .Sum();;
Antoine V
  • 6,998
  • 2
  • 11
  • 34