开发者

How to groupBy a list and map the result to another list

I have the following piece of code:

 public List<myTask> MyTask { get; set; }


 public class myTask
{
    public List<int> ID { get; set; }
    public List<DateTime> Date { get; set; }
    public Decimal Total { get; set; }
 }
 List<myTask> tempTask = new List<myTask>();
 MyTask = new List<myTask>();

I want to do something as follows but having the error message:

MyTask = tempTask.GroupBy(x => x.Date);

Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable,MvcUI.Models.MyTask>>' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)


Edited Code:

I have tried to add the code:

var newtempTask = tempTask.GroupBy(x => x.Date, (Date, values) =>


 new
                    {
                        ID = values.Select(x => x.ID).ToList(),
                        Date = values.Select(x => x.Date).ToList(), Total=values.Select(x => x.Date).ToList() 
                                                                          }); and then 
        foreach (var newitem in newtempTask)
        {
            MyTask.Add(new MyTask
                           {
                               ID = newitem.ID,
                               Date= new开发者_如何学Goitem.Date,Total = newitem.Total
                           });}

I have tried to add the code, please see the above edited code. I am having the error message, Error 7 Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List'


You lack explanations on what you are trying to achieve... I think the following could be what you are asking for: (it selects the first task in each group by date)

 List<myTask> tempTask = new List<myTask>();
 // fill tempTask
 List<myTask> Task = (from t in tempTask
                      group t by t.Date into g
                      select g.First()).ToList();

Or do you perhaps want new tasks for each date with the IDs of all tasks in that group and the sum of the totals?

In that case the query is a little more complex:

   List<myTask> Task2 = (from t in tempTask 
                         group t by t.Date into g
                         select
                           new myTask
                             {
                              ID = new List<int>(g.SelectMany(t => t.ID)),
                              Date = g.Key,
                              Total = g.Sum(t => t.Total)
                             }).ToList();


If you GroupBy you no longer have List<myTask> as type. As you are grouping by a list (is this intended?) you will have to change the declaration of MyTask to:

public IEnumerable<IGrouping<List<DateTime>, myTask>> MyTask { get; set; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜