【问题标题】:How do I group items from a collection using LINQ and return the shaped data according the collection type如何使用 LINQ 对集合中的项目进行分组并根据集合类型返回形状数据
【发布时间】:2010-12-27 15:19:36
【问题描述】:

我有以下收藏

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;
    }

我想做的是通过 myObjectType 类的第一个参数对项目进行分组。

然后对于每个分组,我想做所有最后一个参数的总和。

最后应该以“myObjectType”的形式返回结果

我知道如何以老式的方式进行操作,即循环遍历所有项目并求和。但是,我想学习如何在我刚刚开始的 LINQ 中进行操作。

谁能指出我正确的方向,以便我可以将我的需求转化为 LINQ?

实际上,结果应该是一个包含两个 myObjectType 类型对象的集合,如下所示:

  • 集合中的第一个对象是 (DateTime.Today, 15)
  • 集合中的第二个对象是 (DateTime.Today.AddDays(1), 8)

TIA,

大卫

【问题讨论】:

    标签: linq group-by linq-to-objects


    【解决方案1】:

    给定一个具有这种基本设计的类

    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 来满足您的要求。第一个示例使用流畅的扩展方法语法生成IEnumerable&lt;MyObjectType&gt;

    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() 来生成具体集合。

    【讨论】:

    • 谢谢安东尼,这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2020-03-10
    相关资源
    最近更新 更多