Linq to search for objects and sum results

I have a set of tasks that contain several fields, but more importantly. Duration type Int.

List<Task> tasks = new List<Task>; tasks.Add(new Task{Name= 'Task 1', Duration = 3 }); tasks.Add(new Task{Name= 'Task 2', Duration = 2}); tasks.Add(new Task{Name= 'Task 3', Duration = 1}); tasks.Add(new Task{Name= 'Task 4', Duration = 4}); 

Given the task, I want to find this task in the list, and then summarize everything that came before it. For instance. If I have the task "Task 3", then the result that I want is 5, that is, the tasks before "Task 3" are task 1 and Task 2 with a duration of 3 and 2, respectively, which is 5.

Hope this makes sense and someone can give an answer. Hoping to do this with linq, rather than just looping back.

Thanks in advance.

+4
source share
1 answer

You can use the Linq TakeWhile extension method, followed by Sum :

 var result = tasks.TakeWhile(t => t.Name != "Task 3").Sum(x => x.Duration); 
+4
source

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


All Articles