我想你正在寻找这样的东西:
IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();
查询语法
var query = from c in results
where listOfIds.Any(x => x == c.ID)
select c;
方法语法
var query = results.Where(c => listOfIds.Any(x => x == c.ID));
计算
int numberToSum = query.Sum(x => x.numberToSum);
float numToAverage = query.Average(x => x.numToAverage);
另一种替代方法可以减轻其他成员对性能的一些担忧,但仍然允许查询是友好的(linq-to-entities
, linq-to-sql
):
var calculations = (from c in results
where listOfIds.Any(x => x == c.ID)
group c by 1 into g
select new {
numberToSum = g.Sum(x => x.numberToSum ),
numToAverage = g.Average(x => x.numToAverage),
}).FirstOrDefault();