CustomClass{
int ID;
int numberToSum;
float numToAverage;
}
IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();
我要使用的是我的
IEnumberable<CustomClass>
并选择ID在List<int> listOfIDs
中的所有内容,然后我希望将其numberToSum
值求和并将其保存在变量中并获得numToAverage
属性的平均值并将其保存在变量中。最优雅的方法是什么?
最佳答案
我认为您正在寻找这样的东西:
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();