Find max and min DateTime in Linq group - c#

I'm trying to find the max and min DateTimes from a CSV import.
I have this to import the data from the temp DataTable:
var tsHead = from h in dt.AsEnumerable()
select new
{
Index = h.Field<string>("INDEX"),
TimeSheetCategory = h.Field<string>("FN"),
Date = DdateConvert(h.Field<string>("Date")),
EmployeeNo = h.Field<string>("EMPLOYEE"),
Factory = h.Field<string>("FACTORY"),
StartTime = DdateConvert(h.Field<string>("START_TIME")), //min
FinishTime = DdateConvert(h.Field<string>("FINISH_TIME")), //max
};
Which works fine. I then want to group the data and show the Start time and finish time which is the min / max of the respective fields.
So far I have this:
var tsHeadg = from h in tsHead
group h by h.Index into g //Pull out the unique indexes
let f = g.FirstOrDefault() where f != null
select new
{
f.Index,
f.TimeSheetCategory,
f.Date,
f.EmployeeNo,
f.Factory,
g.Min(c => c).StartTime, //Min starttime should be timesheet start time
g.Max(c => c).FinishTime, //Max finishtime should be timesheet finish time
};
With the thinking that g.Min and g.Max would give me the lowest and highest DateTime for each timesheet (grouped by index)
This doesn't work however... Whats the best way of finding the highest and lowest value of DateTimes within a group?

Try using this
var tsHeadg =
(from h in tsHead
group h by h.Index into g //Pull out the unique indexes
let f = g.FirstOrDefault()
where f != null
select new
{
f.Index,
f.TimeSheetCategory,
f.Date,
f.EmployeeNo,
f.Factory,
MinDate = g.Min(c => c.StartTime),
MaxDate = g.Max(c => c.FinishTime),
});

Related

How to obtain a column total for values in a list - double of anonymous type

I have a database that contains a column of filtered double values that I am trying to get the total of. I have no problem building a collection of values but can't calculate the value combined total.
My Query
var query2 = from r in db.Clocks
where r.WkNo == Current_Wk
group r by r.DailyHrs into g
select new
{
Value = g.Sum( item => item.DailyHrs)
};
var MyList = (query2.ToList());
//The resulting list
//Value = 0.00
//Value = 9.25
//Value = 8.00
How can I determine the total value? i.e 0.00 + 9.25 + 8.00
I have looked at many posts here but can't get it to work.
"firstly materialize the query with .ToList() before calling .Sum():"
[Reference] https://stackoverflow.com/a/20338921/8049376
var query2 = (from r in db.Clocks
where r.WkNo == clock.WkNo
group r by r.DailyHrs into g
select new
{
Value = g.Sum( item => item.DailyHrs)
}).ToList();
var sum = query2.Sum(t => t.Value);

linq to retrieve name instead of id and list in descending order

can u help me to solve this.
i'm retrieving the balance of each heads, and i retrieved the balance of each heads. Now i want to list the balance in the descending order and list the name instead of h_id. i used the code
protected void account_watchlist() {
using(var context = new sem_dbEntities()) {
//ledger && head
var year = DateTime.Now.AddMinutes(318).Year;
var month = DateTime.Now.AddMinutes(318).Month;
var start = new DateTime();
if (month >= 4) {
start = new DateTime(year, 04, 01);
} else if (month < 4) {
start = new DateTime(year - 1, 04, 01);
}
var qr = (from a in context.ledgers
where a.entry_date >= start && a.entry_date < new DateTime(year, month, 1)
join b in context.heads on a.h_id equals b.h_id
group a by a.h_id into sb select new {
sb.FirstOrDefault().h_id,
totalc = sb.Sum(c => c.credit),
totald = sb.Sum(d => d.debit),
balance = sb.Sum(d => d.debit) - sb.Sum(c => c.credit)
}).ToList();
Repeater2.DataSource = qr.ToList();
Repeater2.DataBind();
}
}
You need to use group join of heads with ledgers. It will give you access both to head entity and all related ledgers (in headLedgers collection):
from h in context.heads
join l in context.ledgers.Where(x => x.entry_date >= startDate && x.entry_date < endDate)
on h.h_id equals l.h_id into headLedgers
where headLedgers.Any()
let totalc = headLedgers.Sum(l => l.credit),
let totald = headLedgers.Sum(l => l.debit),
select new {
h.h_id,
h.name,
totalc,
totald,
balance = totald - totalc,
}
I also introduced two range variables for total credit and total debit (consider better names here) to avoid calculating them second time for balance.

Using linq group by statement as a subquery

I have the following query which works fine:
var bands = new List<TimeBand>()
{
new TimeBand(){Region = 10,PeriodId = 5,StartDate = new DateTime(2013, 04, 01),EndDate = new DateTime(2014, 05, 31),DayName = "Friday",StartTime = "00:00",EndTime = "07:00"},
new TimeBand(){Region = 10,PeriodId = 5,StartDate = new DateTime(2013, 04, 01),EndDate = new DateTime(2013, 05, 31),DayName = "Friday",StartTime = "07:00",EndTime = "00:00"},
new TimeBand(){Region = 10,PeriodId = 4,StartDate = new DateTime(2013, 06, 01),EndDate = new DateTime(2013, 08, 31),DayName = "Saturday",StartTime = "20:00",EndTime = "00:00"}
};
var query = (from x in bands
group x by new {x.Region, x.DayName}
into grp
select new TimeBand()
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
StartDate = grp.Min(x => x.StartDate),
EndDate = grp.Max(x => x.EndDate)
}).ToList();
But as I group the results by Region and Dayname I am not getting the other columns in my result i.e StartTime and EndTime.
If this was a SQL query I would have used this grouped results in a subquery and get the other columns as well.
Is there any way of modifying this so I also get the properties which are not included in the group by statement.
Thanks
After grouping source items you have sequence of groups. How you will project these groups is up to you. Usually you select grouping keys and some aggregated values on each group (that is how SQL works). But you can select each group itself, or first item from each group, or some value from last group item:
from b in bands
group b by new { b.Region, b.DayName } into g
select new {
g.Key.Region,
g.Key.DayName,
StartDate = g.Min(x => x.StartDate),
EndDate = g.Max(x => x.EndDate),
AllBandsFromGroup = g,
FirstBand = g.First(),
LastBandPeriod = g.Last().Period
}
Just select out the whole group if you want the keys as well as all of the values for all of the items in the groups:
select grp;
The other option is to select out a sequence of all values of the columns that you want from a group:
select new TimeBand()
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
StartDates = grp.Select(x => x.StartDate),
EndDates = grp.Select(x => x.EndDate)
}
You'd only need to do this if you didn't want to pull down the data for some number of other columns. If you want all of the columns, just use the first option.
var query = (from x in bands
group x by new { x.Region, x.DayName }
into grp
select new
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
MinStartDate = grp.Min(x => x.StartDate),
AllStartDates = grp.Select(k => k.StartDate).ToList(),
EndDate = grp.Max(x => x.EndDate),
AllEndDates = grp.Select(k => k.EndDate).ToList(),
}).ToList();
It seems your are trying to find the minimum start date and time and maximum end date and time for each group. This might be much easier if you combine date and time into a single property.
Otherwise you will need a IComparer<TimeBand> for start date and time and another one for end date and time.
If you don't want to combine date and time you can write methods to get the combined values:
public DateTime GetStart()
{
int hour = int.Parse(StartTime.Substring(0, 2));
int minute = int.Parse(StartTime.Substring(3, 2));
return new DateTime(StartDate.Year, StartDate.Month, StartDate.Day, hour, minute, 0);
}
public DateTime GetEnd()
{
int hour = int.Parse(EndTime.Substring(0, 2));
int minute = int.Parse(EndTime.Substring(3, 2));
return new DateTime(EndDate.Year, EndDate.Month, EndDate.Day, hour, minute, 0);
}
Now you can group the bands and for each group find the minimum start and maximum end:
var query = from x in bands
group x by new
{
x.Region,
x.DayName
}
into grp
select new TimeBand()
{
Region = grp.Key.Region,
DayName = grp.Key.DayName,
StartDate = grp.Min(x => x.StartDate),
StartTime = grp.Min(x => x.GetStart()).ToShortTimeString(),
EndDate = grp.Max(x => x.EndDate),
EndTime = grp.Max(x => x.GetEnd()).ToShortTimeString(),
};
This is however not very elegant. I would prefer to combine date and time in the first place.

Group by date range , count and sort within each group LINQ

I have a collection of dates stored in my object. This is sample data. In real time, the dates will come from a service call and I will have no idea what dates and how many will be returned:
var ListHeader = new List<ListHeaderData>
{
new ListHeaderData
{
EntryDate = new DateTime(2013, 8, 26)
},
new ListHeaderData
{
EntryDate = new DateTime(2013, 9, 11)
},
new ListHeaderData
{
EntryDate = new DateTime(2013, 1, 1)
},
new ListHeaderData
{
EntryDate = new DateTime(2013, 9, 15)
},
new ListHeaderData
{
EntryDate = new DateTime(2013, 9, 17)
},
new ListHeaderData
{
EntryDate = new DateTime(2013, 9, 5)
},
};
I now need to group by date range like so:
Today (1) <- contains the date 9/17/2013 and count of 1
within 2 weeks (3) <- contains dates 9/15,9/11,9/5 and count of 3
More than 2 weeks (2) <- contains dates 8/26, 1/1 and count of 2
this is my LINQ statement which doesn't achieve what I need but i think i'm in the ballpark (be kind if I'm not):
var defaultGroups = from l in ListHeader
group l by l.EntryDate into g
orderby g.Min(x => x.EntryDate)
select new { GroupBy = g };
This groups by individual dates, so I have 6 groups with 1 date in each. How do I group by date range , count and sort within each group?
Introduce array, which contains ranges you want to group by. Here is two ranges - today (zero days) and 14 days (two weeks):
var today = DateTime.Today;
var ranges = new List<int?> { 0, 14 };
Now group your items by range it falls into. If there is no appropriate range (all dates more than two weeks) then default null range value will be used:
var defaultGroups =
from h in ListHeader
let daysFromToday = (int)(today - h.EntryDate).TotalDays
group h by ranges.FirstOrDefault(range => daysFromToday <= range) into g
orderby g.Min(x => x.EntryDate)
select g;
UPDATE: Adding custom ranges for grouping:
var ranges = new List<int?>();
ranges.Add(0); // today
ranges.Add(7*2); // two weeks
ranges.Add(DateTime.Today.Day); // within current month
ranges.Add(DateTime.Today.DayOfYear); // within current year
ranges.Sort();
How about doing this?
Introduce a new property for grouping and group by that.
class ListHeaderData
{
public DateTime EntryDate;
public int DateDifferenceFromToday
{
get
{
TimeSpan difference = DateTime.Today - EntryDate.Date;
if (difference.TotalDays == 0)//today
{
return 1;
}
else if (difference.TotalDays <= 14)//less than 2 weeks
{
return 2;
}
else
{
return 3;//something else
}
}
}
}
Edit: as #servy pointed in comments other developers may confuse of int using a enum will be more readable.
So, modified version of your class would look something like this
class ListHeaderData
{
public DateTime EntryDate;
public DateRange DateDifferenceFromToday
{
get
{
//I think for this version no comments needed names are self explanatory
TimeSpan difference = DateTime.Today - EntryDate.Date;
if (difference.TotalDays == 0)
{
return DateRange.Today;
}
else if (difference.TotalDays <= 14)
{
return DateRange.LessThanTwoWeeks;
}
else
{
return DateRange.MoreThanTwoWeeks;
}
}
}
}
enum DateRange
{
None = 0,
Today = 1,
LessThanTwoWeeks = 2,
MoreThanTwoWeeks = 3
}
and use it like this
var defaultGroups = from l in ListHeader
group l by l.DateDifferenceFromToday into g // <--Note group by DateDifferenceFromToday
orderby g.Min(x => x.EntryDate)
select new { GroupBy = g };
Do you specifically want to achieve the solution in this way? Also do you really want to introduce spurious properties into your class to meet these requirements?
These three lines would achieve your requirements and for large collections willbe more performant.
var todays = listHeader.Where(item => item.EntryDate == DateTime.Today);
var twoWeeks = listHeader.Where(item => item.EntryDate < DateTime.Today.AddDays(-1)
&& item.EntryDate >= DateTime.Today.AddDays(-14));
var later = listHeader.Where(item => item.EntryDate < DateTime.Today.AddDays(-14));
also you then get the flexibility of different groupings without impacting your class.
[Edit: in response to ordering query]
Making use of the Enum supplied above you can apply the Union clause and OrderBy clause Linq extension methods as follows:
var ord = todays.Select(item => new {Group = DateRange.Today, item.EntryDate})
.Union(
twoWeeks.Select(item => new {Group = DateRange.LessThanTwoWeeks, item.EntryDate}))
.Union(
later.Select(item => new {Group = DateRange.MoreThanTwoWeeks, item.EntryDate}))
.OrderBy(item => item.Group);
Note that I'm adding the Grouping via a Linq Select and anonymous class to dynamically push a Group property again not effecting the original class. This produces the following output based on the original post:
Group EntryDate
Today 17/09/2013 00:00:00
LessThanTwoWeeks 11/09/2013 00:00:00
LessThanTwoWeeks 15/09/2013 00:00:00
LessThanTwoWeeks 05/09/2013 00:00:00
MoreThanTwoWeeks 26/08/2013 00:00:00
MoreThanTwoWeeks 01/01/2013 00:00:00
and to get grouped date ranges with count:
var ord = todays.Select(item => new {Group = DateRange.Today, Count=todays.Count()})
.Union(
twoWeeks.Select(item => new {Group = DateRange.LessThanTwoWeeks, Count=twoWeeks.Count()}))
.Union(
later.Select(item => new {Group = DateRange.MoreThanTwoWeeks, Count=later.Count()}))
.OrderBy(item => item.Group);
Output is:
Group Count
Today 1
LessThanTwoWeeks 3
MoreThanTwoWeeks 2
I suppose this depends on how heavily you plan on using this. I had/have a lot of reports to generate so I created a model IncrementDateRange with StartTime, EndTime and TimeIncrement as an enum.
The time increment handler has a lot of switch based functions spits out a list of times between the Start and End range based on hour/day/week/month/quarter/year etc.
Then you get your list of IncrementDateRange and in linq something like either:
TotalsList = times.Select(t => new RetailSalesTotalsListItem()
{
IncrementDateRange = t,
Total = storeSales.Where(s => s.DatePlaced >= t.StartTime && s.DatePlaced <= t.EndTime).Sum(s => s.Subtotal),
})
or
TotalsList = storeSales.GroupBy(g => g.IncrementDateRange.StartTime).Select(gg => new RetailSalesTotalsListItem()
{
IncrementDateRange = times.First(t => t.StartTime == gg.Key),
Total = gg.Sum(rs => rs.Subtotal),
}).ToList(),

linq group by timespan

How is it possible to group by a timespan? What I'm trying to do is get the total minutes, and perform a get timespan from minutes function.
Ultimately I'm trying to get the average time spent on a particular account in one month.
I'm also looking at trying to find the total time spent on a particular account too.
I feel like I'm close but everything I've tried in the select statement doesn't seem to work.
period = new DateTime(2013,1,1);
endPeriod = new DateTime(2013,1,1).AddMonths(1).AddDays(-1);
account.AccountNumber = 1455;
var q = from logs in db.logs
where logs.AccountNumber == account.AccountNumber
where logs.StartDateTime > period && logs.StartDateTime < endPeriod
let time = new TimeSpan(logs.ElapsedHours, logs.ElapsedMinutes, 0).TotalMinutes
group logs by time into g
select new {
AvgTime = g.Average(g.Key)
}
This query is currently returning 5 rows. It should only be returning 1. I'm not sure what I'm doing wrong.
Any suggestions?
Mike
This is what I ended up with:
var result = (from logs in db.logs
where logs.AccountNumber == 1450
where logs.StartDateTime > new DateTime(2013,1,1) && logs.StartDateTime < new DateTime(2013,1,31)
group logs by logs.AccountNumber into g
select new {
AvgTime = (g.Sum(h=>h.ElapsedHours) * 60) + g.Sum(h=>h.ElapsedMinutes) / g.Count(),
TotalTime = (g.Sum(h=>h.ElapsedHours) * 60) + g.Sum(h=>h.ElapsedMinutes)
}).ToList()
.Select(x=> new {
AvgTime = TimeSpan.FromMinutes(x.AvgTime),
TotalTime = TimeSpan.FromMinutes(x.TotalTime)
});
Your query is a bit confusing - you're grouping by a value (timespan) but then apparently trying to compute an average of the key values, rather than an average of the items within each group. If that is truly the case try this:
period = new DateTime(2013,1,1);
endPeriod = new DateTime(2013,1,1).AddMonths(1).AddDays(-1);
account.AccountNumber = 1455;
var q = from logs in db.logs
where logs.AccountNumber == account.AccountNumber
&& logs.StartDateTime > period && logs.StartDateTime < endPeriod
let time = new TimeSpan(logs.ElapsedHours, logs.ElapsedMinutes, 0).TotalMinutes
group logs by time into g
select new {
Time = g.Key
}
var averageTime = q.Average(i => i.Time);
g.Key will only give you one value for each group, which is why you are seeing 5 records (I'm assuming that your data will produce 5 groups).

Categories