Technology Lover
Technology Lover

Reputation: 259

How to display the total number of hours for each day using linq in each day's TextBox control?

I am a new to LINQ-to-Entities world and I am trying to display (the sum of hours for each task in each day in the week) in the TextBox that is specified for the total number of hours of each day.

I have the following tables in the database:

Task Table: TaskId, Description
Sheet Table: SheetId, WeekNumber
SheetEntry Table: SheetEntryId, SheetId, TaskId
EntryDetail Table: EntryDetailId, SheetEntryId, WorkDay, Hours

And I have the following TextBoxs in my aspx page:

<asp:TextBox ID="txtSun" runat="server" CssClass="input-mini" placeholder="Sunday's Total"></asp:TextBox>
<asp:TextBox ID="txtMon" runat="server" CssClass="input-mini" placeholder="Monday's Total"></asp:TextBox>
<asp:TextBox ID="txtTue" runat="server" CssClass="input-mini" placeholder="Tuesday's Total"></asp:TextBox>
<asp:TextBox ID="txtWed" runat="server" CssClass="input-mini" placeholder="Wednesday's Total"></asp:TextBox>
<asp:TextBox ID="txtThu" runat="server" CssClass="input-mini" placeholder="Thursday's Total"></asp:TextBox>
<asp:TextBox ID="txtFri" runat="server" CssClass="input-mini" placeholder="Friday's Total"></asp:TextBox>
<asp:TextBox ID="txtSan" runat="server" CssClass="input-mini" placeholder="Saturday's Total"></asp:TextBox>

I wrote the following LINQ query that displays the total sum of hours in each day in the week, but I am not sure if it is working well:

var query = (from detail in context.EntryDetail
                            group detail by new { detail.Workday } into g
                            select new {
                                Date = g.Key.Workday,
                                Total = g.Sum(x => x.Hours)
                            }).ToList();

So how can I display the total number of hours of each day in its specified TextBox control?

Please note that the week starts from Sunday.

Upvotes: 0

Views: 546

Answers (1)

messi
messi

Reputation: 38

Best way to write the query would be:

This will give the only the total hours.
var query1 = context.EntryDetail.GroupBy(_x => _x.WorkDay).Select(_x => _x.Sum(c => c.Hours)).ToList();

This will give the a pair in form of .
var query2 = context.EntryDetail.GroupBy(_x => _x.WorkDay).Select(_x => new {day =_x.Key, totalhours = _x.Sum(c => c.Hours)}).ToList();

Then you can add to the textbox based of the day you get in this query.

foreach (var item in query2)
{
switch(item.day)
{
case "Sunday" : texSun.Text = item.totalhours;
break;
case "Monday" : texMon.Text = item.totalhours;
break;
//Similarly for other cases
}
}

Upvotes: 1

Related Questions