在IEnumerable中定义具有特定ID的项目

时间:2012-10-01 15:01:42

标签: c# .net linq list ienumerable

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


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

我希望如何处理这些内容,请点击我的IEnumberable<CustomClass>,然后选择List<int> listOfIDs中ID的所有内容,然后我希望将numberToSum的值加起来并将其保存在变量中并获取numToAverage属性的平均值并将其保存在变量中。

最优雅的方法是什么?

4 个答案:

答案 0 :(得分: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-entitieslinq-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();

答案 1 :(得分: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);

答案 2 :(得分: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;

答案 3 :(得分: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;