How can check following code to catch divided by zero error?
active = (g.Sum(x => x.Kullanim_Reaktif) / g.Sum(x => x.kullanim_T0)) * 100
I want something like this:
if(g.Sum(x => x.kullanim_T0) == 0)
{
return 1;
}
else
{
return g.Sum(x => x.kullanim_T0);
}
Can I write if-else in above linq code line (g.Sum(x => x.kullanim_T0))? And how?
Thanks.
active = (g.Sum(x => x.kullanim_T0) == 0 ? 1 : g.Sum(x => x.Kullanim_Reaktif) / g.Sum(x => x.kullanim_T0)) * 100
but more efficient to do:
var kSum = g.Sum(x => x.kullanim_T0);
active = (kSum == 0 ? 1 : g.Sum(x => x.Kullanim_Reaktif) / kSum ) * 100
Related
We have a table with a large amount of data and I do not want to load it at once for my dxDataGrid.
I want to implement paging with Skip / Take which is supplied from the dxDataGrid's DataSourceLoadOptions.
This is my controller:
[HttpGet]
public async Task<Object> GetSalesOrdersWithTotals(DataSourceLoadOptions loadOptions)
{
try
{
var results = await SalesOrderService.GetSalesOrdersWithTotals(loadOptions.Skip, loadOptions.Take, 40);
loadOptions.Skip = 0;
loadOptions.Take = 0;
return DataSourceLoader.Load(results, loadOptions);
}
catch (Exception ex)
{
return Json(new { code = "422", success = false, message = "Unable to fetch sales orders with totals - " + ex.ToString() });
}
}
This is the service that returns the data:
public async Task<IEnumerable<SalesOrderWithTotals>> GetSalesOrdersWithTotals(int skip, int take, int defaultPageSize)
{
if (take == 0)
{
//Fix for passing a 0 take
take = defaultPageSize;
}
var salesOrderWithTotals =
from o in _context.SalesOrder
select new SalesOrderWithTotals
{
SalesOrderId = o.SalesOrderId,
Net = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum(),
Tax = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage /100),
Gross = _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() + _context.SalesOrderItem.Where(it => it.SalesOrderId == o.SalesOrderId).Select(it => it.Qty == null ? 0 : it.Qty.Value * it.UnitPrice == null ? 0 : it.UnitPrice.Value).Sum() * (o.Tax.Percentage / 100),
Name = o.Customer.Name,
CustomerOrderNumber = o.CustomerOrderNumber,
Contact = o.Contact,
OrderDate = o.OrderDate
};
return await salesOrderWithTotals.Skip(skip).Take(take).ToListAsync();
}
Looking at SQL profiler, this takes the first 40 records but of course the dxDataGrid is not aware of the total count of records so pagination is not available.
What would be the best method to achieve what I want in this case?
Many thanks
You must do an extra query to get the count of your SalesOrder and keep it in for example salesOrderCount. Then keep the Load method return data as bellow.
LoadResult result = DataSourceLoader.Load(results, loadOptions);
LoadResult has a parameter called totalCount so set it with the real count of your data:
result.totalCount = salesOrderCount;
and then
return result;
Now the dxDataGrid is aware of the total count of records.
The usage and limit (quotas) section of firebase clearly says that the firebase firestore security rule will allow only an expression with a maximum length of 1000 per request.But it does n't mentioning anything about the expressions.Can somebody explain about
1)What is an expression ?
2)How expression are evaluated ?
3)What are the possible way to reduce the length of evaluating expression ?
Good question on an undocumented subject. My understanding is the following:
1) Anything that is evaluated
2) Example:
match /somepath {
allow update: if request.resource.data.counter == resource.data.counter + 1
}
Here you have 10 expressions
request.resource.data.counter => 4
resource.data.counter => 3
1 => 1
== and + => 1 each = 2
3) Calculate only once...
Example:
match /somepath {
allow update: if request.resource.data.notchange1 == resource.data.notchange1 => 8 expressions
&& request.resource.data.notchange2 == resource.data.notchange2 => 8
&& request.resource.data.test1 > 0 => 6
&& request.resource.data.timestamp == request.time => 7
&& request.resource.data.counter == resource.data.counter + 1; => 10
}
=> 39 expressions in total
Better version:
match /somepath {
allow update: if checkupdate(); => 1
function checkupdate() {
let mapafter = request.resource.data; => 3
let map = request.resource; => 2
return mapafter.notchange1 == map.notchange1 => 5
&& mapafter.notchange2 == map.notchange2 => 5
&& mapafter.test1 > 0 => 4
&& mapafter.timestamp == request.time => 5
&& mapafter.counter == map.counter + 1; => 7
}
=> 32 expressions in total
I have the below query that gets Name and TotalPoints as follows:
var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(Convert.ToInt32(this.ShopInstanceID), 10000, false)
.Where(row => row.RecievedPoints != "n/a")
.GroupBy(row => new { row.Name })
.Select(g => new
{
TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))),
Name = g.Key.Name
})
select data).ToList();
I will have data like below:
TotalPoints Name
5 A
10 B
5 C
15 D
5 E
If we observe the above list 5 is most common. I have to fetch that value from "gradeData".
How can I get that?
var mostCommon = gradeData.GroupBy(x => x.TotalPoints)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.First();
The query below gives you the most common point along with all of its associated names:
var result = gradeData.GroupBy(x => x.TotalPoints)
.OrderByDescending(x => x.Count())
.Select(g => new
{
TotalPoints = g.Key,
Names = g.Select(x => x.Name).ToList()
})
.First();
I've seen dozens of posts similar to this, but I just can't get it to work.
Using asp.net MVC framework, I have a table named Contributions that contains a "ContributionDate" column and an "Amount" column. I'm loading the dates and amounts to display in a chart:
var results = db.Contributions.Where(c => c.Amount > 0);
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
results.ToList().ForEach(c => xValue.Add(c.ContributionDate));
results.ToList().ForEach(c => yValue.Add(c.Amount));
The above works. Now I'd liked to sum (i.e., total) the Amounts for each year. I've seen examples that are similar to the following, but I'm clearly clueless (in this example, the compiler doesn't like the "c.ContributionDate" in the new{} statement):
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new {Amount = c.Sum(b => b.Amount), Date=c.ContributionDate});
Thanks for your help!
When you perform a GroupBy, the key by which you're grouping elements is represented by the Key property.
Try this:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate )
.Select(c => new { Amount = c.Sum(b => b.Amount), Date = c.Key });
But this will group items by the entire ContributionDate value, not just by the year. To do that, you'd have to do something like this:
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = new DateTime(c.Key, 1, 1)
});
But since this appears to be Entity Framework, you probably need to use the CreateDateTime function:
using System.Data.Entity;
...
var results = db.Contributions
.Where(c => c.Amount > 0)
.GroupBy( c => c.ContributionDate.Year)
.Select(c => new
{
Amount = c.Sum(b => b.Amount),
Date = EntityFunctions.CreateDateTime(c.Key, 1, 1, 0, 0, 0)
});
How can i get the start and end date of a DatePeriod object?
$today = new \DateTime(date('Y-m-d')); // 2012-05-30
$period = new \DatePeriod($today, new \DateInterval('P1M'), 1);
$stats = new UsageStatistics($period);
class UsageStatistics
{
protected $period, $sentEmailCount, $autoSentEmailCount;
public function __construct(\DatePeriod $period)
{
$this->period = $period;
// Current logged in user and email repository
$user = $this->getUser();
$repo = $this->getEmailRepository();
// Get the start and end date for the given period
$startDate = ...
$endDate = ...
$result = $repo->getAllSentCount($user, $startDate, $endDate);
// Assigning object properties
}
public function getSentEmailCount() { return $this->sentEmailCount; }
public function getAutoSentEmailCount() { return $this->autoSentEmailCount; }
}
DatePeriod only implements the Traversable interface and has no other methods to either access elements or retrieve them.
You can do something easy to get start/end dates:
$periodArray = iterator_to_array($period);
$startDate = reset($periodArray);
$endDate = end($periodArray);
I'm using PHP 5.6.9 and it seems that you can use the properties end and start to access your beginning and end DateTime objects:
$p = new DatePeriod($s, $i, $e);
$startTime = $p->start; //returns $s
$endTime = $p->end; //returns $e
The PHP documentation doesn't seem to reflect this. I did a print_r of a DatePeriod object and got the following output:
DatePeriod Object
(
[start] => DateTime Object
(
[date] => 2015-06-01 00:00:00.000000
[timezone_type] => 3
[timezone] => America/Los_Angeles
)
[current] => DateTime Object
(
[date] => 2015-06-08 00:00:00.000000
[timezone_type] => 3
[timezone] => America/Los_Angeles
)
[end] => DateTime Object
(
[date] => 2015-06-08 00:00:00.000000
[timezone_type] => 3
[timezone] => America/Los_Angeles
)
[interval] => DateInterval Object
(
[y] => 0
[m] => 0
[d] => 7
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] =>
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
[recurrences] => 1
[include_start_date] => 1
)
It seems that properties current and interval are also visible.
The solution posted by #hakre and #Boby is not correct.
The $endDate is end of the period when PERIOD % INTERVAL = 0.
All other cases $endDate will be END - PERIOD.
$startingDate = new DateTime($startingDay);
$startingDate->modify('previous day');
$startingDate->modify('next Sunday');
$endingDate = new DateTime($endingDay);
$endingDate->modify('next day');
$period = new DatePeriod($startingDate, new DateInterval('P1W'), $endingDate);