how to filter and sum using linq

后端 未结 3 1352
你的背包
你的背包 2021-01-19 05:01

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  
{  
            


        
相关标签:
3条回答
  • 2021-01-19 05:08

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

    0 讨论(0)
  • 2021-01-19 05:09

    I know LINQ should not have side-effects, but for what it's worth ...

    int totalIncomeOfToList = 0;  
    List<Employee> toList = myList
        .Where(emp => emp.empType == 1)
        .Select(emp => { totalIncomeOfToList += emp.income; return emp; })
        .ToList();
    
    0 讨论(0)
  • 2021-01-19 05:09

    Try this for getting the total income

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

    If you also want the list of filtered employees then:

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

    The performance will be slightly better with a foreach, but this way the code will be much clear and precise.

    0 讨论(0)
提交回复
热议问题