如何使用LINQ对集合中的项进行分组,并根据集合类型返回成形数据
我有以下收藏如何使用LINQ对集合中的项进行分组,并根据集合类型返回成形数据,linq,group-by,linq-to-objects,Linq,Group By,Linq To Objects,我有以下收藏 public IQueryable<myObjectType > GetWorkCellLoadGraphDataByIdDummy() { IList<myObjectType> workCellLoadGraphDataCollection = new List<myObject>() { new myObjectType(DateTime.Today.AddHo
public IQueryable<myObjectType > GetWorkCellLoadGraphDataByIdDummy()
{
IList<myObjectType> workCellLoadGraphDataCollection = new List<myObject>()
{
new myObjectType(DateTime.Today.AddHours(8).AddMinutes(30), 1),
new myObjectType(DateTime.Today.AddHours(10).AddMinutes( 10 ), 6 ),
new myObjectType(DateTime.Today.AddHours(13).AddMinutes( 30 ),8 ),
new myObjectType(DateTime.Today.AddDays(1).AddHours(8).AddMinutes(30), 1),
new myObjectType(DateTime.Today.AddDays(1).AddHours( 10 ).AddMinutes( 10 ), 5 ),
new myObjectType(DateTime.Today.AddDays(1).AddHours( 13 ).AddMinutes( 30 ), 2 )
};
// Write some LINQ code to group data according to first parameter
// Perform sum of last parameter
// Shape the data to be in the form of myObjectType
// return result;
}
公共IQueryable GetWorkCellLoadGraphDataByIdDummy()
{
IList workCellLoadGraphDataCollection=新列表()
{
新的MyObject类型(DateTime.Today.AddHours(8).AddMinutes(30),1),
新的MyObject类型(DateTime.Today.AddHours(10).AddMinutes(10),6),
新的MyObject类型(DateTime.Today.AddHours(13)、AddMinutes(30)、8),
新的MyObject类型(DateTime.Today.AddDays(1)、AddHours(8)、AddMinutes(30)、1),
新的MyObject类型(DateTime.Today.AddDays(1)、AddHours(10)、AddMinutes(10)、5),
新的MyObject类型(DateTime.Today.AddDays(1).AddHours(13).AddMinutes(30),2)
};
//根据第一个参数编写一些LINQ代码来分组数据
//执行最后一个参数的求和
//将数据形状设置为myObjectType的形式
//返回结果;
}
我要做的是根据myObjectType类的第一个参数对项目进行分组
然后,对于每个分组,我要计算最后所有参数的总和
最后,结果应该以“myObjectType”的形式返回
我知道如何用老式的方法来做,也就是循环所有的项目,做算术。然而,我想学习如何在LINQ中实现这一点,这是我刚刚开始的
有人能给我指出正确的方向,以便我能将我的需求转化为LINQ吗
实际上,结果应该是包含两个myObjectType类型的对象的集合,如下所示:
- 集合中的第一个对象是(DateTime.Today,15)
- 集合中的第二个对象是(DateTime.Today.AddDays(1),8)
David给了一个有这种基本设计的班级
class MyObjectType
{
public MyObjectType(DateTime date, int count)
{
this.MyDate = date;
this.MyCount = count;
}
public DateTime MyDate { get; set; }
public int MyCount { get; set; }
}
您可以按照以下方式使用LINQ来满足您的需求。第一个示例使用fluent扩展方法语法生成IEnumerable
var query = collection.GroupBy(obj => obj.MyDate.Date)
.Select(grp =>
new MyObjectType(grp.Key, grp.Sum(obj => obj.MyCount))
);
第二个版本实现了相同的结果,但使用了更像SQL的查询表达式语法
var query = from obj in collection
group obj by obj.MyDate.Date into grp
let mySum = grp.Sum(item => item.MyCount)
select new MyObjectType(grp.Key, mySum);
从那里,您可以使用扩展方法
AsQueryable
生成IQueryable
结果,或者ToList()
/ToArray()
生成具体的集合。谢谢Anthony,这正是我需要的。