Get Maximum Value from multiple rows of multiple columns using LINQ? - linq

I'm using LINQPad to evaluate my linq query. My query goes like this:
from o in MyTableFirst
join p in MyTableSecond on o.TheName equals p.TheName
where p.TheName == "CBA-123" && !p.Removed &&
(o.ReturnPeriod ==100 || o.ReturnPeriod ==10)
select new {
HMax1 = o.MaxValue1,
HMax2 = o.MaxValue2,
HMax3 = o.MaxValue3
}
This query can return 0 or some number of rows.
In LINQPad, it return me something like this:
HMax1 HMax2 HMax3
21.1 null 22.5
null 24.6 11.5
Now, how am I going to get the Maximum value out for these return rows & columns?
I'm expecting return of 24.6.Thank You

How about this:
(from o in db.MyTableFirsts
join p in db.MyTableSeconds on o.TheName equals p.TheName
where p.TheName == "CBA-123" && !p.Removed &&
(o.ReturnPeriod == 100 || o.ReturnPeriod == 10)
select new
{
Maximum = Math.Max(
Math.Max((float)(o.MaxValue1 ?? 0), (float)(o.MaxValue2 ?? 0)),
(float)(o.MaxValue3 ?? 0)
)
}).OrderByDescending(o => o.Maximum).FirstOrDefault();
Or instead of .OrderByDescending(o => o.Maximum).FirstOrDefault(), you can use .Max(o => o)

Try this:
(
from o in MyTableFirst
join p in MyTableSecond on o.TheName equals p.TheName
where p.TheName == "CBA-123" && !p.Removed &&
(o.Level ==100 || o.Level ==10)
//combine all of the numbers into one list
let listOfNumbers = new List<double?>{o.MaxValue1,o.MaxValue2,o.MaxValue3}
//select the list
select listOfNumbers
)
.SelectMany(c => c) //combine all the lists into one big list
.Max(c => c) //take the highst number

Related

LINQ EF AND VS2017

I wrote a query and worked on LINQPAD
from x in FacilityData
from y in FavInformation
where y.UserID == 1 && x.ID == y.FacilityID
select new
{
xID = x.ID,
xDistrictName = (from y in _Ilcelers
where y.ID == x.DistrictID
select y.IlceAd).FirstOrDefault(),
xName = x.Name,
Value = (from o in Tags
from p in Table_tags
where o.Prefix != null && o.Prefix == p._NAME && o.Facility == y.FacilityID
orderby p.İd descending
select new
{
FType = o.TagType,
Name = o.TagsName,
Value = p._VALUE,
Time = p._TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
}
result
the result is perfect
but does not work in visual studio,
Value = (from o in DB.Tags
from p in DB.table_tags
where o.Prefix != null && o.Prefix == p.C_NAME && o.Facility == 11
orderby p.id descending
select new
{
FType=o.TagType,
Name = o.TagsName,
Value = p.C_VALUE,
Time = p.C_TIMESTAMP
}).Take(Tags.Count(h => h.Facility == y.FacilityID))
and it gives an error.
I guess the part with .Take() doesn't work because it's linq to EF.
error:
Limit must be a DbConstantExpression or a Db Parameter Reference Expression. Parametre name: count]
error image
thank you have a good day
Not sure but I will just throw it in. If you are talking about linq to ef/sql, it is possible they dont know a thing about C#. If take() would be the problem try to get the select result local first by doing .tolist(). Afterwards use your take funtion.
.ToList().Take(Tags.Count(h => h.Facility == y.FacilityID))

LINQ Aggregate results with Many to Many Relationship

I am currently working with this schema
This is how my LINQ currently looks
var regionResults = (
from p in _context.Projects
from pr in p.Regions
where (data.RegionId == null || pr.RegionId == data.RegionId)
group p by pr.RegionId into g
join q in _context.Regions on g.Key equals _context.Regions.First().Id
select new Models.ViewModels.ProjectBreakdownViewModel.Regions
{
RegionName = q.Name,
TotalCount = g.Count(),
RejectedCount = g.Count(e => e.SubmissionStatusId == 2),
DeniedCount = g.Count(e => e.SubmissionStatusId == 3)
});
this is what it is currently producing, albeit incorrect
This is what I need it to be...
I know the problem is with this line, essentially
join q in _context.Regions on g.Key equals _context.Regions.First().Id
I don't know how to do this without the use of .First(), there doesn't seem to be a way to do it. I'm close I just don't know how to finish this.
If you have an collection of ProjectRegions in you Region entity, you can do this:
var result= context.Regions
.Where(r=> data.RegionId == null || r.Id == data.RegionId)
.Select(r=> new
{
RegionName = r.Name,
TotalCount = r.ProjectRegions.Count(),
RejectedCount = r.ProjectRegions.Count(e => e.Project.SubmissionStatusId == 2),
DeniedCount = r.ProjectRegions.Count(e => e.Project.SubmissionStatusId == 3)
});
ProjectRegion entity should have two nav properties, Project and Region, use them to navigate and create the corresponding conditions

Single link query where clause to take only `n` of each type from a single model/table

Having a table Entities with a column type (between other columns) how can I select only n entities from type A and m entities from type b in a single linq query where clause? Is it possible?
I am looking for something like this:
var x = from s in db.Entities
where s.type == `A` && (????) < n
|| s.type == `B` && (????) < m
select s
Current solution with combined queries:
var x = entities.Where(e => e.type == `A`).Take(n).Union(
entities.Where(e => e.type == `B`).Take(m));
You could use GroupBy:
var x = db.Entities.GroupBy(x => x.type)
.Where(g => g.Key == "A" || g.Key == "B")
.SelectMany(g => g.Key == "A" ? g.Take(n) : g.Take(m));
But I don't know why you don't like your Union-based solution - it should result in just one query sent to the database anyway.

Linq: Where count greater than value

I have a linq query which accepts a list of date and port combinations. This query has to return data from a table, CruiseCalendar, where these combinations are found, but only when the count is greater than one. I cant work out the groupby and count syntax. var shipRendezvous is where I'm stuck.
var dateAndPort = (from r in context.CruiseCalendar
where r.ShipId == shipId
&& r.CruiseDayDate >= dateRange.First
&& r.CruiseDayDate <= dateRange.Last
select new DateAndPort
{
Date = r.CruiseDayDate,
PortId = r.PortId
});
var shipRendezvous = (from r in context.CruiseCalendar
where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
&& d.PortId == r.PortId))
orderby r.CruiseDayDate // (Added since first posting)
select r).ToList();
regards, Guy
If I understood you correctly, you are filterting for every set which matches any of the results of dateAndPort and then want to group it by itsself to get a count. Of the grouping results you only want those resultsets, which occur more then once.
var shipRendezvous = (from r in context.CruiseCalendar
where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
&& d.PortId == r.PortId))
select r)
.GroupBy(x => x.CruiseDayDate) //Groups by every combination
.Where(x => x.Count() > 1) //Where Key count is greater 1
.ToList();
Based on your comment, you want to flatten the list again. To do so, use SelectMany():
var shipRendezvous = (from r in context.CruiseCalendar
where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
&& d.PortId == r.PortId))
select r)
.GroupBy(x => x.CruiseDayDate) //Groups by every combination
.Where(x => x.Count() > 1) //Where Key count is greater 1
.SelectMany(x => x)
.ToList();

Linq strangeness

I was receiving repeating rows from this linq query:
public static Func<DataContext, string, IQueryable<Building>>
GearFilteredBuildings =
CompiledQuery.Compile((DataContext db, string filter) =>
from b in db.Building
join r in db.Router on b equals r.Building
orderby !b.Active
where filter.Length == 5 && r.Name.Substring(1, 5).ToLower() == filter
|| filter.Substring(0, 3) == r.Name.Substring(3, 3).ToLower()
select b);
After some fiddling, I got the distinct Buildings with this:
public static Func<DataContext, string, IQueryable<Building>>
GearFilteredBuildings =
CompiledQuery.Compile((DataContext db, string filter) =>
(from b in db.Building
join r in db.Router on b equals r.Building
orderby !b.Active
where filter.Length == 5 && r.Name.Substring(1, 5).ToLower() == filter
|| filter.Substring(0, 3) == r.Name.Substring(3, 3).ToLower()
group b by b.Id into g
select g) as IQueryable<Building>);
Is this an acceptable solution? How else might this be done?
Not sure (couldn't test it IDE) but select...join...lalala can replaced with Linq-Chain syntax:
db.Routers
.Where(r => filter.Length == 5 && r.Name.Substring(1, 5).ToLower() == filter || filter.Substring(0, 3) == r.Name.Substring(3, 3).ToLower())
.GroupBy(r => r.Building)
.Select(g => g.Key)
.OrderBy(b => !b.Active)
Also: as I can see no joins are really requred in your query, as you have navigation properties (r.Building)in your model.
Or another approach could be used, select all needed buildings, and use .Distinct() afterwards:
db.Routers
.Where (r => filter.Length == 5 && r.Name.Substring(1, 5).ToLower() == filter || filter.Substring(0, 3) == r.Name.Substring(3, 3).ToLower())
.Select(r => r.Building)
.Distinct()
.OrderBy(b => !b.Active)

Resources