Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to filter and sum using linq

Tags:

c#

linq

what is the best LINQ approach for with no performance loss? how could we do the same thing using LINQ iterating the list only once?

class Employee  
{  
    string name ...;  
    string age .....;  
    int empType ...;  
    int income ...;  
}  

List<Employee> myList ...;  
List<Employee> toList...;  
int totalIncomeOfToList = 0;  

foreach(Employee emp in myList)  
{  
    if(emp.empType == 1)  
    {  
        toList.Add(emp);  
        totalIncomeOfToList += emp.income;  
    }  
}  
like image 903
Nith Avatar asked Dec 06 '22 04:12

Nith


1 Answers

(I'm assuming you want the filtered list as well - the other answers given so far only end up with the sum, not the list as well. They're absolutely fine if you don't need the list, but they're not equivalent to your original code.)

Well you can iterate over the original list just once - and then iterate over the filtered list afterwards:

var toList = myList.Where(e => e.empType == 1).ToList();
var totalIncomeOfToList = toList.Sum(e => e.income);

Admittedly this could be a bit less efficient in terms of blowing through the processor cache twice, but I'd be surprised if it were significant. If you can prove that it is significant, you can always go back to the "manual" version.

You could write a projection with a side-effect in it, to do it all in one pass, but that's so ugly that I won't even include it in the answer unless I'm really pressed to do so.

like image 110
Jon Skeet Avatar answered Dec 29 '22 18:12

Jon Skeet