简体   繁体   中英

C#: Groupby, Difference of data in dataset

Following is my dataset which I get from the database:

Id -- Date -- ClockIn -- ClockOut

1  --  1/1/2016 -- 1/1/2016:09:00:00 -- 1/1/2016:17:03:00

1  --  1/2/2016 -- 1/1/2016:09:00:00 -- 1/1/2016:11:30:00   

1  --  1/2/2016 -- 1/1/2016:13:00:00 -- 1/1/2016:15:03:00

Expected result

1 -- 1/1/2016(8 hrs) -- 09:00:00 -- 17:03:00 
1 -- 1/2/2016(4 hrs) -- 09:00:00 -- 11:30:00
                     -- 13:00:00 -- 15:03:00  

Question: I want a group-by on Date field and difference of clockIn/out and its sum for the day

Here is the code what I am trying but not able to get it work:

var resultSet = from newSet in Dtinfo.AsEnumerable()
    group newSet by new
    {
        uid = newSet.Field<int>("UID"),
        gDate = newSet.Field<DateTime>("wDate"),
        inTime = newSet.Field<DateTime>("punchIn"),
        outTime = newSet.Field<DateTime>("punchOut"),

        location = newSet.Field<String>("locName"),
        typeName = newSet.Field<String>("typeName"),

    } into counter
    select new
    {
        UID = counter.Key.uid,
        wDate=counter.Key.gDate,
        punchIn = counter.Key.inTime,
        punchOut = counter.Key.outTime,
        locName= counter.Key.location,
        typeName= counter.Key.typeName,
        diff = (counter.Key.outTime - counter.Key.InTime).TotalHours,

    };

I am getting the difference but I need the group by and sum to work as well.

Any light on the path would be helpful.

here is the query. I am returning anonymous class with

  • Date - date which was grouped by
  • TotalHours - sum of all entries for that day
  • Entries - entries, another anonymous class

It is probably better to replace them with named classes.

var res = from newset in Dtinfo.AsEnumerable()
              group newset by newset.Field<DateTime>("wDate")
                  into counter
                  select new
                  {
                      Date = counter.Key,
                      TotalHours = counter.Select(a => a.Field<DateTime>("punchOut") - a.Field<DateTime>("punchIn")).Sum(a => a.TotalHours),
                      Entries = counter.Select(a => new
                      {
                          uid = a.Field<int>("UID"),
                          gDate = a.Field<DateTime>("wDate"),
                          /*other fields here
                           * 
                           * 
                           */
                      })
                  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM