如何筛选和使用LINQ总结 [英] how to filter and sum using linq

查看:107
本文介绍了如何筛选和使用LINQ总结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是没有性能损失的最好办法LINQ?我们如何使用LINQ遍历列表一次做同样的事情?



 类Employee 
{
字符串名称...;
串年龄.....;
INT的empType ...;
INT收入...;
}

名单,LT;员工> myList中......;
名单,LT;员工> ...了ToList;
INT totalIncomeOfToList = 0;

的foreach(在myList中员工EMP)
{
如果(emp.empType == 1)
{
toList.Add(EMP);
totalIncomeOfToList + = emp.income;
}
}


解决方案

(我假设你的希望的过滤列表以及 - 鉴于到目前为止只的总和,而不是列表结束以及其他的答案他们是绝对没问题,如果你不需要列表中,但他们并不等同于原来的代码)



那么你可以通过迭代的原始列表中只有一次 - 然后遍历通过的过滤列表算账:

  VAR了ToList = myList.Where(E => e。的empType == 1).ToList(); 
VAR totalIncomeOfToList = toList.Sum(E => e.income);



诚然,这可能是一个的的在通过吹方面效率较低处理器高速缓存两次,但我会感到惊讶,如果它是显著。如果你能证明它的的显著,你可以随时返回到手动版本。



您的可以写的投射在它的副作用,做这一切在一通,但是这是这么丑,我不会甚至还包括它的答案,除非我真的按这样做。


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;  
    }  
}  

解决方案

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

这篇关于如何筛选和使用LINQ总结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆