Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c# - how to filter and sum using 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;  
    }  
}  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...