3
CustomClass{
int ID;
int numberToSum;
float numToAverage;
}


IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();

我希望对这些进行处理,将我的IEnumberable<CustomClass>并选择 ID 中的所有值List<int> listOfIDs,然后我希望将其numberToSum值求和并将其保存在变量中并获取numToAverage属性的平均值并将其保存在多变的。

最优雅的方法是什么?

4

4 回答 4

7

我想你正在寻找这样的东西:

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();
于 2012-10-01T15:06:37.823 回答
1

我认为它是这样的:

var matchingIdsList = results.Where(x => listsOfIDs.Any(y => y == x.Id));
var sum = matchingIdsList.Sum(x=> x.numberToSum);
var average = matchingIdsList.Average(x=> x.numToAverage);
于 2012-10-01T15:08:56.607 回答
0

我会这样做 - 不是很优雅但更有效:

// Load IDs into a hashset so Contains is O(1) not O(n)
var hashSetOfIDs = new HashSet<int>(listOfIDs);

// Aggreagate count and both sums in one pass, then calculate average.
var result = results.Where(cc => hashSetOfIDs.Contains(cc.ID)).Aggregate(
    new { Count = 0, Sum = 0, AverageSum = 0f },
    (a, cc) => new {
        Count = a.Count + 1,
        Sum = a.Sum + cc.numberToSum,
        AverageSum = a.AverageSum + cc.numToAverage },
    a => new { 
        Sum = a.Sum,
        Average = a.Count > 0 ? a.AverageSum / a.Count : float.NaN });

// Extract results
var sum = result.Sum;
var average = result.Average;
于 2012-10-01T15:11:34.213 回答
0
var results = MethodToPopulateIEnumerable();
var listOfIDs = MethodToGetListOfIDs();

int numberToSum = 0;
float numberToAverage = 0;

var selected = results.Where(c => listOfIDs.Contains(c.ID)).Select(c =>
  {
    numberToSum += c.numberToSum;
    numberToAverage += c.numToAverage;
    return c;
  }).ToList();

float average = numberToAverage/selected.Count;
于 2012-10-01T15:15:26.177 回答