how to filter and sum using linq

后端 未结 3 1376
你的背包
你的背包 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题