Please consider this simple class
public class SEANCE
{
int ID_SEANCE {get;set;}
DateTime SEA_DATE {get;set;}
}
It's for a fitness management app, the SEANCE class is the session table for the members.
Here's my starting query to show the number of the sessions grouped by day Hour
var lst = ctx.SEANCES
.GroupBy(o => o.SEA_DATE.Hour)
.Select(g => new ChartData()
{
DT = new DateTime(2017, 01, 01, g.Key, 0, 0),
VALUE = g.Count()
});
return lst.OrderBy(a => a.DT).ToList();
as you can see, it returns the total number of sessions grouped by hour.
What I want instead is the average number of sessions by day and grouped by hour, and that's where I am a little lost :p
here what i mean
for example at 18, 1500 is corresponding to the total number of sessions at that time.
what i want instead is the average number by day
hope it make sense now :)
ctx.SEANCES.Count() / lst.Count(), but that seems like database source so better to use the result:
var groups = ctx.SEANCES
.GroupBy(s => s.SEA_DATE.Hour)
.OrderBy(g => g.Key)
.Select(g => new ChartData()
{
DT = g.First().SEA_DATE,
VALUE = g.Count()
})
.ToList();
var averageByHour = groups.Average(c => c.VALUE);
var averageByDay = groups.GroupBy(s => s.DT.Day).Average(g => g.Sum(c => c.VALUE));
Related
Grouping is an area of LINQ that I haven't quite managed to get my head around yet. I have the following code:
var subTrips = tbTripData
.Where(t => selectedVehicleIds.Contains(t.VehicleID))
.Join(tbSubTripData,
t => t.TripID,
s => s.TripID,
(t, s) => new { t = t, s = s })
.Select(r =>
new SubTrip
{
VehicleID = r.t.VehicleID,
TripID = r.t.TripID,
Sequence = r.s.Sequence,
TripDistance = r.s.TripDistance,
Odometer = r.s.Odometer
})
.ToList();
I'm trying to figure out a LINQ query that will look at subTrips and for each VehicleID, find the first Odometer, i.e. the Odometer corresponding to the lowest TripID and Sequence values.
I've been poking at it for an hour but just can't figure it out. Can anyone offer some advice before I give up and write procedural code to do it?
UPDATE: To clarify, Sequence is the sequential number of each subtrip within a trip. So what I'm looking for is the Odometer from the first subtrip for each vehicle when the subtrips within each grouped VehicleID are ordered by TripID then by Sequence.
I'm not 100% what you're looking for. But this might get you started in the right direction.
var groupedList = (from s in subTrips
group s by s.VehicleID
into grp
select new
{
VehicleID = grp.Key,
Odometer = grp.OrderBy(ex => ex.TripID).Select(ex => ex.Odometer).First(),
TripID = grp.Min(ex => ex.TripID)
}
).ToList();
This will return the VehicleID, the Odometer corresponding to the lowest TripID, and the lowest TripID.
class YearlyData
{
MonthlyData[] monthlyData = new MonthlyData[12];
}
class MonthlyData
{
int Salary;
}
Given I have a List<YearlyData>, how can I find total salary for a given month for the number of years.
Example for three years I need total salary given for 1st month & subsequent months.
If you want the sum of all the Salaries for April:
List<YearlyData> l;
l.Sum(yd => yd.monthlyData[3].Salary);
If I misread your question, and you really want all the salaries for April & subsequent months (in the year)
l.Sum(yd => yd.monthlyData.Skip(3).Sum());
Something like this:
list.SelectMany(x => x.monthlyData
.Select((m, i) => new {month = i+1,
data = m.Salary}
))
.GroupBy(x => x.month)
.Select(x => new {month = x.Key,
total = x.Sum(m => m.data)});
This will give you a list with twelve entries, one for each month along with the total amount of that month.
I have following query:
var accounts =
from account in context.Accounts
from guranteer in account.Gurantors
select new AccountsReport
{
CreditRegistryId = account.CreditRegistryId,
AccountNumber = account.AccountNo,
DateOpened = account.DateOpened,
};
return accounts.AsEnumerable()
.Select((account, index) => new AccountsReport()
{
RecordNumber = FormattedRowNumber(account, index + 1),
CreditRegistryId = account.CreditRegistryId,
AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)}).OrderByDescending(c => c.StateChangeDate);
It works fine except one problem and that is it returns records number in reverse order like 3, 2,1 because of .OrderByDescending(c => c.StateChangeDate);
Can I show the record number in ascendeing order while keeping the records in descending order.
Please suggest.
Thanks
Try using OrderBy on RecordNumber and then ThenByDescending on StateChangeDate
.OrderBy(c => c.RecordNumber).ThenByDescending(c => c.StateChangeDate);
I have a list of objects. E.g. List<coin> where they contain a string(denom) and int(year).
If the list contains:
"Quarter", 1954
"Quarter", 1990
"Penny", 1925
"Nickel", 1900
"Nickel", 2000
How can I get a resultant list where it contains the unique values with just the most recent year? E.g.:
"Quarter", 1990
"Penny", 1925
"Nickel", 2000
You can do this by grouping by name, then either ordering and taking the first result, or by using something like MaxBy from MoreLINQ:
var query = coins.GroupBy(x => x.Name)
.Select(g => g.MaxBy(x => x.Year));
or
var query = coins.GroupBy(x => x.Name)
.Select(g => g.OrderByDescending(x => x.Year).First());
You can do this using group by like:
var query = from coin in myList
group coin by coin.Name into grouped
select new
{
Name = grouped.Key
Year = grouped.Max(x => x.Year)
};
For another sample like this, check out "max - grouped" in the 101 Linq examples: http://msdn.microsoft.com/en-us/vcsharp/aa336747#maxGrouped
var coins = new Coin[] { ... };
var recentCoins =
from coin in coins
group coin by coin.Denom into g
select new
{
Denom = g.Key,
MostRecentYear = g.Max(c => c.Year)
};
I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote
var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
.Where(x => x.TripPath.PathNumber == pathnum)
.Select(x => x.TripPath.TripPathLink.Link.Speed).Min();
I am not able to use group by and where together it keeps giving error .
My query should
Select all the values.
filter it through the where clause (pathnum).
Groupby the road Name
finally get the min value.
can some one tell me what i am doing wrong and how to achieve the desired result.
Thanks,
Pawan
It's a little tricky not knowing the relationships between the data, but I think (without trying it) that this should give you want you want -- the minimum speed per road by name. Note that it will result in a collection of anonymous objects with Name and Speed properties.
var data = newTrips.Where(x => x.TripPath.PathNumber == pathnum)
.Select(x => x.TripPath.TripPathLink.Link)
.GroupBy(x => x.Road.Name)
.Select(g => new { Name = g.Key, Speed = g.Min(l => l.Speed) } );
Since I think you want the Trip which has the minimum speed, rather than the speed, and I'm assuming a different data structure, I'll add to tvanfosson's answer:
var pathnum = 1;
var trips = from trip in newTrips
where trip.TripPath.PathNumber == pathnum
group trip by trip.TripPath.TripPathLink.Link.Road.Name into g
let minSpeed = g.Min(t => t.TripPath.TripPathLink.Link.Speed)
select new {
Name = g.Key,
Trip = g.Single(t => t.TripPath.TripPathLink.Link.Speed == minSpeed) };
foreach (var t in trips)
{
Console.WriteLine("Name = {0}, TripId = {1}", t.Name, t.Trip.TripId);
}