Select Min and Max LINQ - c#

select description, min(date), max(date), sum(value1), sum(value2) from table
where description = 'Axxx' and filter = 'L'
group by description
How to perform this query using Linq / C#?

Not tested, but the following should work:
table
.Where(x=>x.description=="Axxx" && x.filter=="L")
.GroupBy(x=>x.description)
.Select(x=>new {
description=x.Key,
mindate=x.Min(z=>z.date),
maxdate=x.Max(z=>z.date),
sumvalue1=x.Sum(z=>z.value1),
sumvalue2=x.Sum(z=>z.value2)
});

something like this should work. not tested
var q = from b in table
group b by b.Owner into g
where description = 'Axxx'
select new
{
description = g.description ,
date = g.min(),
date = g.max(),
value1= g.Sum(item => item.value1),
value2= g.Sum(item => item.value2),
};

That should work
var q = from s in db.table
where description = 'Axxx' and filter = 'L'
group s by s.description into g
select new {YourDescription = g.description, MaxDate = g.Max(s => s.date) }
That answer may help, too .. here

Related

LINQ Query for GroupBy and Max in a Single Query

I have the following LINQ query but i want to modify it that I want to group by staffId and pick only those records whose ObservationDate is Max for each staffId.
from ob in db.TDTObservations.OfType<TDTSpeedObservation>()
select new
{
Id = ob.ID,
AcademicYearId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().AcademicYearID,
observationDate = ob.ObservationDate,
schoolId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().SchoolID,
staffId=ob.Teachers.FirstOrDefault().ID
};
var observations =
from ob in db.TDTObservations.OfType<TDTSpeedObservation>()
select new {
Id = ob.ID,
AcademicYearId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().AcademicYearID,
observationDate = ob.ObservationDate,
schoolId = ob.Teachers.FirstOrDefault().Classes.FirstOrDefault().SchoolID,
staffId=ob.Teachers.FirstOrDefault().ID
};
var result = from o in observations
group o by o.staffId into g
select g.OrderByDescending(x => x.observationDate).First();
what about this: hereby you first group your entries (Teachers) by their ID together and then from each group (grp) you pick that one with the latest ObservationDate
var observations = from d in db.TDTObservations.OfType<TDTSpeedObservation>()
group d by d.Teachers.FirstOrDefault().ID into grp
select grp.OrderByDescending(g => g.ObservationDate).FirstOrDefault();

How can I order the output of my long LINQ query by a double and then a string?

I have the following LINQ query:
summaries = from m in _master
join d in _detail on pk + m.RowKey equals d.PartitionKey into outer
from d in outer.DefaultIfEmpty()
select new
{
Position = m.Position,
Title = m.Title,
Detail = ((d == null) ? 0 : 1),
PartitionKey = m.PartitionKey,
RowKey = m.RowKey,
Modified = m.Modified,
ModifiedBy = m.ModifiedBy
} into split
group split by split.Title into g
select new AdminSummary
{
Position = g.Last().Position,
Title = g.Key,
DetailCount = g.Sum(s => s.Detail),
PartitionKey = g.Last().PartitionKey,
RowKey = g.Last().RowKey,
Modified = g.Last().Modified,
ModifiedBy = g.Last().ModifiedBy
};
The query works well but now I would like to do an order by on Position (double) followed by Title (string).
Can someone advise how I can do this?
Can someone tell me how to do the order by?
It's pretty easy:
summaries = summaries.OrderBy(item =>item.Position).ThenBy(item =>item.Title);
Also you can use OrderByDescending() and ThenByDescending() if you need them in descending order
Do this after your above query.
summaries = from s in summaries
orderby s.Position,s.Title
select s

How can I filter results of one LINQ query based on another?

Given the following:
DP_DatabaseTableAdapters.EmployeeTableAdapter employeetableAdapter = new DP_DatabaseTableAdapters.EmployeeTableAdapter();
DP_Database.EmployeeDataTable employeeTable = employeetableAdapter.GetData();
var leadEmployees = from e in employeeTable
where e.IsLead == true
select e;
DP_DatabaseTableAdapters.LaborTicketTableAdapter tableAdapter = new DP_DatabaseTableAdapters.LaborTicketTableAdapter();
DP_Database.LaborTicketDataTable table = tableAdapter.GetDataByDate(date.ToString("MM/dd/yyyy"));
var totHours = from l in table
join e in leadEmployees on l.EmployeeID equals e.EmployeeID
group l by l.EmployeeID into g
orderby g.Key
select new
{
EmployeeID = g.Key,
HoursWorked = g.Sum(s => s.HoursWorked)
};
Total hours correctly filters the results based on the leadEmployee's list of people who have the IsLead bit set to true.
I would like to know how to do this with a where clause, I have attempd to use leadEmployees.Contanis but it wants a whole EmployeeRow...
How can I add what looks to be part of an IN clause to a where filter to replace the join?
var totHours = from l in table
where ??????
group l by l.EmployeeID into g
orderby g.Key
select new
{
EmployeeID = g.Key,
HoursWorked = g.Sum(s => s.HoursWorked)
};
The contains will only want a whole EmployeeRow if you are selecting whole employee roles. You can either:
leadEmployees.Select(e => e.id).contains
OR
leadEmployees.Count(e => e.id == l.id) > 0
Both will work. (Excuse slightly rushed lack of consideration for syntax accuracies).
This should work:
var leadEmployees = from e in employeeTable
where e.IsLead == true
select e.EmployeeID;
var totHours = from l in table
where leadEmployees.Contains(l.EmployeeID)
group l by l.EmployeeID into g
orderby g.Key
select new
{
EmployeeID = g.Key,
HoursWorked = g.Sum(s => s.HoursWorked)
};

Linq Merge Queries

I have two queries that I would like to merge. This might be a left outer join, but it seems different.
The first query selects distinct stuff from a table:
var d = from d in db.Data
select (d.ID, d.Label, Value = 0).Distinct;
Lets suppose this returns the following:
{1,"Apple",0}
{2,"Banana",0}
{3,"Cabbage",0}
I then have another query that makes a different selection:
var s = from d in db.Data
where d.Label != "Apple"
select (d.ID, d.Label, d.Value);
This returns:
{2,"Banana",34}
{3,"Cabbage",17}
I then want a third query that joins the d and s together based upon their ID and their Label. I want the result to look like this:
{1,"Apple",0}
{2,"Banana",34}
{3,"Cabbage",17}
I'm basically just updating the numbers in the third query, but I have no idea how I should be doing this. It feels like it should be a simple join, but I just cannot get it to work.
This should work:
var query1 = from d in db.Data
select new { d.ID, d.Label, Value = 0 }.Distinct();
var query2 = from d in db.Data
where d.Label != "Apple"
select new { d.ID, d.Label, d.Value };
var result =
from d1 in query1
join d2 in query2 on new { d1.ID, d1.Label } equals new { d2.ID, d2.Label } into j
from d2 in j.DefaultIfEmpty()
select new
{
d1.ID,
d1.Label,
Value = d2 != null ? d2.Value : d1.Value
};
Note: are you sure you want to join on the ID and the label ? It seems rather strange to me... the label shouldn't be part of the key, so it should always be the same for a given ID
Here is one using method chain, which is my personal favorite.
var one = db.Data.Select(f => new {f.Id, f.Label, Value = 0});
var two = db.Data.Select(f => f).Where(f => f.Label != "Apple");
var three = one.Join(two, c => c.Id, p => p.Id, (c, p) => new {c.Id, c.Label, p.Value});
Could you just do
var s = from d in db.Data
select new
{
Id = d.ID,
Label = d.Label,
Value = (d.Label == "Apple" ? 0 : d.Value)
};

Linq query with left join and group

I'm unable to convert this SQL query into a working linq statement
select sum(cena), id_auta, max(servis)
from dt_poruchy left outer join mt_auta on dt_poruchy.id_auta=mt_auta.id
where dt_poruchy.servis>=3 group by id_auta;
I tryed something like this but i cant handle the select statement
var auta = from a in MtAuta.FindAll()
join p in DtPoruchy.FindAll() on a equals p.MtAuta into ap
from ap2 in ap.DefaultIfEmpty()
where ap2.SERVIS >= 3
group ap2 by ap2.ID into grouped
select new {
I'll appreciate any help!
Based on the limited information provided (which tables are certain fields from?), here is what I came up with.
var auta = from a in MtAuta.FindAll()
let p = a.DtPoruchys.Where(s => s.SERVIS >= 3)
select new
{
Id = a.Id,
CenaSum = p.Sum(c => c.Cena),
Servis = p.Max(s => s.SERVIS)
};
I've reached this solution (supposing "cena" belongs to MtAuta.FindAll()):
var auta = from e in
(from a in DtPoruchy.FindAll()
where a.SERVIS >= 3
join p in MtAuta.FindAll() on a.MtAuta equals p.Id into ap
from ap2 in ap.DefaultIfEmpty()
select new
{
Cena = ap.cena,
IdAuta = a.MtAuta,
Servis = a.servis
})
group e by e.IdAuta into g
select new
{
Cena = g.Sum(e => e.cena),
IdAuta = g.Key,
Servis = g.Max(e => e.servis)
};
I am not sure which table cena and servis are coming from but to create grouped sum you do something like.
select new { Sum = grouped.Sum( x => x.cena ) }
and to get max
select new { Max = grouped.Group.Max( x => x.servis ) }
Here is a good reference for you.
MSDN - 101 LINQ Samples
I've modified your solution little bit and i got it working like this:
var auta = from jo in
(
from a in MtAuta.FindAll()
join p in DtPoruchy.FindAll() on a equals p.MtAuta into ap
from ap2 in ap.DefaultIfEmpty()
where ap2.SERVIS >= 3
select new
{
Cena = ap2.CENA,
Idauto = ap2.ID_AUTA,
Servis = ap2.SERVIS
}
)
group jo by jo.Idauto into g
select new
{
Cena = g.Sum(jo => jo.Cena),
IdAuto = g.Key,
Servis = g.Max(jo => jo.Servis)
};
I just curious if this is the best solution?

Categories

Resources