SQL to Linq with aggregate function - c#

I'm trying to do this in LINQ.
Can you guys help me to do this?
There some tool to help me with this conversion?
SELECT
CODIGO_DEPENDENCIA,
SUM(COALESCE(LOCAL_MOVEL, 0)) AS LOCAL_MOVEL,
SUM(COALESCE(LOCAL_FIXO, 0)) AS LOCAL_FIXO,
SUM(COALESCE(DDD_MOVEL, 0)) AS DDD_MOVEL,
SUM(COALESCE(DDD_FIXO, 0)) AS DDD_FIXO,
SUM(COALESCE(EXTERNA_INTERNACIONAL, 0)) AS EXTERNA_INTERNACIONAL
FROM (
SELECT
CODIGO_DEPENDENCIA,
CASE WHEN TIPO = 'SELM' THEN SUM(VALOR) END AS LOCAL_MOVEL,
CASE WHEN TIPO = 'SELF' THEN SUM(VALOR) END AS LOCAL_FIXO,
CASE WHEN TIPO = 'SENM' THEN SUM(VALOR) END AS DDD_MOVEL,
CASE WHEN TIPO = 'SENF' THEN SUM(VALOR) END AS DDD_FIXO,
CASE WHEN TIPO = 'SEI' THEN SUM(VALOR) END AS EXTERNA_INTERNACIONAL
FROM CAD_BILHETES
WHERE ID_PRODUTO IS NULL
AND ID_COMPETENCIA = 60
AND CODIGO_DEPENDENCIA IN (14, 160)
AND TIPO IN ('SEI', 'SELM', 'SENF', 'SELF', 'SENM')
AND VALOR <> 0
GROUP BY TIPO,CODIGO_DEPENDENCIA
) TAB
GROUP BY CODIGO_DEPENDENCIA

Obviously untested. Also, uncertain if null tests are needed or how they will react through SQL translation. It may be preferable to change the first query to return 0 when not matching and then just sum the results, but I wasn't sure the datatype of the columns.
var tab = from cb in CAD_BILHETES
where cb.ID_PRODUTO == null && cb.ID_COMPETENCIA == 60 && (new[] { 14, 160 }).Contains(cb.CODIGO_DEPENDENCIA) &&
(new[] { "SEI", "SELM", "SENF", "SELF", "SENM" }).Contains(cb.TIPO) && cb.VALOR != 0
group cb by new { cb.TIPO, cb.CODIGO_DEPENDENCIA } into cbg
select new { cbg.Key.CODIGO_DEPENDENCIA,
LOCAL_MOVEL = (cbg.Key.TIPO == "SELM" ? cbg.SUM(cb => cb.VALOR) : null),
LOCAL_FIXO = (cbg.Key.TIPO == "SELF" ? cbg.SUM(cb => cb.VALOR) : null),
DDD_MOVEL = (cbg.Key.TIPO == "SENM" ? cbg.SUM(cb => cb.VALOR) : null),
DDD_FIXO = (cbg.Key.TIPO == "SENF" ? cbg.SUM(cb => cb.VALOR) : null),
EXTERNA_INTERNACIONAL = (cbg.Key.TIPO == "SEI" ? cbg.SUM(cb => cb.VALOR) : null),
};
var ans = from cb in tab
group cb by cb.CODIGO_DEPENDENCIA into cbg
select new {
CODIGO_DEPENDENCIA = cbg.Key,
LOCAL_MOVEL = cbg.Sum(cb => cb.LOCAL_MOVEL == null ? 0 : cb.LOCAL_MOVEL),
LOCAL_FIXO = cbg.Sum(cb => cb.LOCAL_FIXO == null ? 0 : cb.LOCAL_FIXO),
DDD_MOVEL = cbg.Sum(cb => cb.DDD_MOVEL == null ? 0 : cb.DDD_MOVEL),
DDD_FIXO = cbg.Sum(cb => cb.DDD_FIXO == null ? 0 : cb.DDD_FIXO),
EXTERNA_INTERNACIONAL = cbg.Sum(cb => cb.EXTERNA_INTERNACIONAL == null ? 0 : cb.EXTERNA_INTERNACIONAL)
};

Related

Prevent Entity Framework query from being evaluated locally

I have this query that is being partially evaluated locally and I am wondering how to prevent it.
It seems to be the conditional select that is causing the problem.
var fetchQuery = (
from udg in _entities.UberDirectGroups.AsNoTracking()
join uber in _entities.Ubers.AsNoTracking()
on udg.Id equals uber.Id
let memberCount = (
from t in _entities.UberDirects.AsNoTracking()
join u in _entities.Ubers.AsNoTracking()
on t.UberToId equals u.Id
where t.UberFromId == udg.Id && !u.Deleted
select u.UberTypeId == (byte)UberType.User ? 1 :
u.UberTypeId == (byte)UberType.Department ? u.Department.Users.Where(user => user.Deleted == false).Count() :
u.UberTypeId == (byte)UberType.Office ? u.tblOffice.tblDepartment.SelectMany(d => d.Users).Where(user => user.Deleted == false).Count() :
u.UberTypeId == (byte)UberType.ProjectGroup ? u.Group.GroupMembers.Select(pm => pm.User).Where(user => user.Deleted == false).Count() :
u.UberTypeId == (byte)UberType.Role ? _entities.Roles.Where(r => r.RoleDataId == u.tblRoleData.Id).Select(r => r.tblUser).Where(user => user.Deleted == false).Count() : 0
).Sum()
where
udg != null &&
uber != null &&
uber.InstanceId == instanceId &&
(!isSearch || udg.Name.Contains(searchText))
select new TargetGroupProjection
{
id = udg.Id,
name = udg.Name,
created = uber.Date,
toCount = memberCount
}
);

Why FirstOrDefault get this exception? Sequence contains no matching element exception

I hope you can help me to my code after I change the data type of the following I get this exception "Sequence contains no matching element exception. ". And I am sure this because of FirstOrDefault() Extension.
LandId - long
ShowMapPoint - string
Development - string
Location - string
MapPointX - string
MapPointY - string
AreaSize - from decimal? into long?
Premium - from decimal? into long?
TransactionPrice - from decimal? into long?
This is my code:
var result = _context.DwPropertyMasters.Where(x => x.ShowMapPoint == "Y")
.Select(x => new
{
x.LandId,
a = x.Development == null || x.Development == "" ? x.Location : x.Development,
x.MapPointX,
x.MapPointY,
AreaSize = x.AreaSize ?? 0,
Premium = x.Premium ?? 0,
b = (x.Premium == 0 ? null : x.Premium) * 100000000 / (x.AreaSize == 0 ? null : x.AreaSize) ?? 0,
c =
_context.DwPropertyDetails.Where(
z => (z.TransactionPrice > 0 || z.TransactionPrice != null) && z.LandId == x.LandId)
.GroupBy(z => z.LandId)
.Select(g =>
(g.Sum(p => p.TransactionPrice) == 0 ? null : g.Sum(p => p.TransactionPrice)) /
(g.Sum(p => p.ActualSize) == 0 ? null : g.Sum(p => p.ActualSize)) ?? 0)
.FirstOrDefault(),
d =
((x.AreaSize2 == 0 ? null : x.AreaSize2) == 0
? 0
: (x.Premium == 0 ? null : x.Premium) * 100000000 / (x.AreaSize2 == 0 ? null : x.AreaSize2)) ??
0,
x.LandType,
e =
_context.DwPropertyDetails.Where(
y => (y.TransactionPrice > 0 || y.TransactionPrice != null) && y.LandId == x.LandId)
.Select(y => new
{
a = 1
}).Count()
});
Your problem is in the sum of the Premium and TransactionPrice
If you grouping doesn't contain an item with a value, then it will try to sum null values. That can't work.
I would change it as follows:
(g.All(p => p.TransactionPrice == null) ? null : g.Where(p => p.TransactionPrice != null).Sum(p => p.TransactionPrice))
and
(g.All(p => p.ActualSize == null) ? null : g.Where(p => p.ActualSize != null).Sum(p => p.ActualSize)))
First check if everything is null, then it is null, else sum the values.
But you need to edit your code further, your current code would enable situations like 123 / null or null / 123. Which would also be a exception.
It is hard to understand what you are doing. It is way too complex with all these inline if's. And on line 13 you have:
z.TransactionPrice > 0 || z.TransactionPrice != null.
You might as well remove z.TransactionPrice > 0, because the second part allows all values (not null), including everything smaller than 0.
The 'Sequence contains no matching element' exception is typically something I'd expect when you use .First(). Not .FirstOrDefault().
Based on your code and what I think you want to achieve I have rewritten the query:
var result = _context.DwPropertyMasters.Where(x => x.ShowMapPoint == "Y")
.Select(x => new
{
x.LandId,
a = x.Development == null || x.Development == "" ? x.Location : x.Development,
x.MapPointX,
x.MapPointY,
AreaSize = x.AreaSize ?? 0,
Premium = x.Premium ?? 0,
b = (x.AreaSize == 0) ? 0 : (x.Premium * 100000000 / x.AreaSize ?? 0),
c = _context.DwPropertyDetails.Where(z => z.TransactionPrice > 0 && z.LandId == x.LandId)
.GroupBy(z => z.LandId)
.Select(g => g.Sum(p => p.ActualSize) == 0 ? 0 : (g.Sum(p => p.TransactionPrice) / g.Sum(p => p.ActualSize) ?? 0)
.FirstOrDefault(),
d = (x.AreaSize2 == 0) ? 0 : (x.Premium * 100000000 / x.AreaSize2 ?? 0),
x.LandType,
e = _context.DwPropertyDetails.Count(y => y.TransactionPrice > 0 && y.LandId == x.LandId)
});
I do not know if this works as you intended (and works at all since I didn't test this), but it is shorter and I hope more readable.
Keep in mind that this query is executed in sql server, so there is no need to check for null values. The only thing that must be prevented is to divide by zero. If we consider the next line:
b = (x.AreaSize == 0) ? 0 : (x.Premium * 100000000 / x.AreaSize ?? 0)
If:
x.AreaSize is null then (x.Premium * 100000000 / null ?? 0) => null ?? 0 => 0.
x.AreaSize = 0 then the result = 0.
x.Premium is null then the result is null / value ?? 0 => null ?? 0 => 0.
x.Premium = 0 then the result = 0.

How to check null while joining multiple tables by LINQ?

var Data = (from s in _context.PRD_RecipeItem.AsEnumerable()
where s.RecipeID == _RecipeID
from i in _context.Sys_ChemicalItem.Where(x => x.ItemID == s.ItemID).DefaultIfEmpty()
from u in _context.Sys_Unit.Where(x => x.UnitID == s.UnitID).DefaultIfEmpty()
from st in FinalStock.AsEnumerable().Where(x => x.ItemID == s.ItemID).DefaultIfEmpty()
from sup in _context.Sys_Supplier.Where(x => x.SupplierID == (st==null? 0: st.SupplierID)).DefaultIfEmpty()
select new PRDChemProdReqItem
{
ItemID = s.ItemID,
ItemName = (i == null ? null : i.ItemName),
RequiredQty = s.RequiredQty,
RequiredUnit = s.UnitID,
RequiredUnitName = (u == null ? null : u.UnitName),
RequsitionQty = s.RequiredQty,
ApproveQty = s.RequiredQty,
ApproveUnit = s.UnitID,
ApproveUnitName = (u == null ? null : u.UnitName),
PackSizeName = "",
PackQty = 0,
SizeUnitName = "",
RequisitionUnit = s.UnitID,
RequisitionUnitName = (u == null ? null : u.UnitName),
StockQty = (st == null ? null : (Math.Round(Convert.ToDecimal(st.ClosingQty), 2)).ToString()),
SupplierID = (st == null ? 0 : st.SupplierID),
SupplierName = (sup == null ? null : sup.SupplierName),
ItemSource = "Via Requisition"
}).ToList();
This is my code. When st is null, then I'm getting An exception of type System.Reflection.TargetException. How to solve this issue. Thanks in Advance.
Why don't you use join? This will take care of your null values.
See more details including source code here: http://msdn.microsoft.com/en-us/library/bb311040.aspx

Cannot implicitly convert type 'System.DateTime?' to 'int?' C# Linq

The Code: It highlights the bottom most part where I can trying to tell Linq to find the shipto column and update the datetimestamp on the other table by a certain amount of minutes and tells me that I cannot implicitly convert type 'System.DateTime?' to 'int?' and I am unsure of how to continue...
var TestingLinq = (from a in db.shp_master
join b in db.shp_status on a.serialnbr equals b.serialnbr into b_join
from b in b_join.DefaultIfEmpty()
where
a.shipto == "1022a" &&
a.status == "s" &&
b.status == "s" &&
a.shpreq == 0
group new {a, b} by new {
a.serialnbr,
a.trailer,
a.shipto
} into g
orderby
g.Key.serialnbr
select new RecieveTruck {
SerialNumber = g.Key.serialnbr,
TrailerNumber = (g.Key.trailer ?? "N/A"),
Shipped = g.Min(p => p.b.datetimestamp),
ETA =
g.Key.shipto == "1026" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(180) :
g.Key.shipto == "2020" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(195) :
g.Key.shipto == "2017" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(180) :
g.Key.shipto == "nor" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(180) : null
});
return View(TestingLinq);
Gives me the error in the title....
I was trying to convert this SQL Query to Linq:
SELECT a.serialnbr, ISNULL(a.trailer, 'N/A') AS 'trailer', MIN(b.datetimestamp) AS 'datetimestamp',
CASE WHEN a.shipto = '1026' THEN DATEADD(mi, 180, MIN(b.datetimestamp))
WHEN a.shipto = '2020' THEN DATEADD(mi, 195, MIN(b.datetimestamp))
WHEN a.shipto = '2017' THEN DATEADD(mi, 180, MIN(b.datetimestamp))
WHEN a.shipto = 'nor' THEN DATEADD(mi, 180, MIN(b.datetimestamp))
ELSE NULL END AS 'eta'
FROM shp_master AS a LEFT OUTER JOIN shp_status AS b ON a.serialnbr = b.serialnbr
WHERE a.shipto = '1022a' AND a.status = 's' AND b.status = 's' AND a.shpreq = 0
GROUP BY a.serialnbr, a.trailer, shipto
ORDER BY a.serialnbr
In your comment, you specified that RecieveTruck.ETA is an int?, but you're assigning it by doing
ETA = g.Key.shipto == "1026" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(180) :
g.Key.shipto == "2020" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(195) :
g.Key.shipto == "2017" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(180) :
g.Key.shipto == "nor" ? (System.DateTime?)Convert.ToDateTime(g.Min(p => p.b.datetimestamp)).AddMinutes(180) : null
And that will resolve to a DateTime?. You'll need to choose one or the other. It looks like you're looking for ETA to be a DateTime?, though, so I'd just change that property type and you should be good to go.

streamline linq query

I have tried using Left outer join using linq. It gives me the same result anytime i change my report parameters.
var _result = (from ls in SessionHandler.CurrentContext.LennoxSurveyResponses
from ml
in SessionHandler.CurrentContext.MailingListEntries
.Where(mle => mle.SurveyCode == ls.SurveyCode).DefaultIfEmpty()
from lists
in SessionHandler.CurrentContext.MailingLists
.Where(m => m.MailingListId == ml.MailingListId).DefaultIfEmpty()
from channel
in SessionHandler.CurrentContext.Channels
.Where(ch => ch.ChannelId == lists.ChannelId).DefaultIfEmpty()
from tmChannelGroup
in SessionHandler.CurrentContext.ChannelGroups
.Where(tcg => tcg.ChannelGroupId == channel.ChannelGroupId).DefaultIfEmpty()
from dmChannelGroup
in SessionHandler.CurrentContext.ChannelGroups
.Where(dcg => dcg.ChannelGroupId == tmChannelGroup.ParentChannelGroupId).DefaultIfEmpty()
from amChannelGroup
in SessionHandler.CurrentContext.ChannelGroups
.Where(acg => acg.ChannelGroupId == dmChannelGroup.ParentChannelGroupId).DefaultIfEmpty()
where (model.ChannelId != 0 && channel.ChannelId == model.ChannelId ||
model.TMId != 0 && channel.ChannelGroupId == model.TMId ||
model.DistrictId != 0 && dmChannelGroup.ChannelGroupId == model.DistrictId ||
model.AreaId != 0 && amChannelGroup.ChannelGroupId == model.AreaId ||
model.AreaId == 0 && amChannelGroup.ChannelGroupId == model.LoggedChannelGroupId ||
model.DistrictId == 0 && dmChannelGroup.ChannelGroupId == model.LoggedChannelGroupId ||
model.TMId == 0 && tmChannelGroup.ChannelGroupId == model.LoggedChannelGroupId ||
model.ChannelId == 0 && tmChannelGroup.ChannelGroupId == model.LoggedChannelGroupId)
&& (ml.EmailDate != null || ml.LetterDate != null || ml.EmailBounce == null)
select ls).ToList();
I have this LINQ query which is repeated (sort of) based on the model value. How would I be able to shorten this query..if I could just use one var object instead of using a bunch for different parameters..as you see this code is repeated.
if (model.ChannelId != 0)
{
var _result =
(from ls in SessionHandler.CurrentContext.LennoxSurveyResponses
join ml in SessionHandler.CurrentContext.MailingListEntries on ls.SurveyCode equals ml.SurveyCode
join m in SessionHandler.CurrentContext.MailingLists on ml.MailingListId equals m.MailingListId
join ch in SessionHandler.CurrentContext.Channels on m.ChannelId equals ch.ChannelId
where ch.ChannelId == model.ChannelId
&& ml.EmailBounce == null || ml.EmailBounce.Equals(false)
select ls).ToList();
var _SentSurveys =
(from ml in SessionHandler.CurrentContext.MailingListEntries
join m in SessionHandler.CurrentContext.MailingLists on ml.MailingListId equals m.MailingListId
join ch in SessionHandler.CurrentContext.Channels on m.ChannelId equals ch.ChannelId
where ch.ChannelId == model.ChannelId
&& (ml.EmailDate != null || ml.LetterDate != null || ml.EmailBounce == null)
select ml).ToList();
model.SentSurveys = _SentSurveys.Count() > 0 ? _SentSurveys.Count() : 0;
model.CompletedSurveys = _result.Count() > 0 ? _result.Count() : 0;
model.PercentageComplete = model.SentSurveys != 0 ? model.CompletedSurveys / model.SentSurveys : 0;
//model.Referring = _result.Average(m => Convert.ToInt32(m.Question1Answer));
model.Referring = Math.Round(_result.Select(m => string.IsNullOrEmpty(m.Question1Answer) ? 0 : Double.Parse(m.Question1Answer)).Average());
model.ServicePerformance = Math.Round(_result.Select(m => string.IsNullOrEmpty(m.Question2Answer) ? 0 : Double.Parse(m.Question2Answer)).Average());
model.InstallPerformance = Math.Round(_result.Select(m => string.IsNullOrEmpty(m.Question3Answer) ? 0 : Double.Parse(m.Question3Answer)).Average());
model.ReferringLennox = Math.Round(_result.Select(m => string.IsNullOrEmpty(m.Question4Answer) ? 0 : Double.Parse(m.Question4Answer)).Average());
}
else if (model.TMId != 0)
{
var _result =
(from ls in SessionHandler.CurrentContext.LennoxSurveyResponses
join ml in SessionHandler.CurrentContext.MailingListEntries on ls.SurveyCode equals ml.SurveyCode
join m in SessionHandler.CurrentContext.MailingLists on ml.MailingListId equals m.MailingListId
join ch in SessionHandler.CurrentContext.Channels on m.ChannelId equals ch.ChannelId
where ch.ChannelGroupId == model.TMId
select ls).ToList();
var _SentSurveys =
(from ml in SessionHandler.CurrentContext.MailingListEntries
join m in SessionHandler.CurrentContext.MailingLists on ml.MailingListId equals m.MailingListId
join ch in SessionHandler.CurrentContext.Channels on m.ChannelId equals ch.ChannelId
where ch.ChannelGroupId == model.TMId
&& (ml.EmailDate != null || ml.LetterDate != null || ml.EmailBounce == null)
select ml).ToList();
model.SentSurveys = _SentSurveys.Count() > 0 ? _SentSurveys.Count() : 0;
model.CompletedSurveys = _result.Count() > 0 ? _result.Count() : 0;
model.PercentageComplete = model.SentSurveys != 0 ? model.CompletedSurveys / model.SentSurveys : 0;
model.Referring = _result.Select(m => string.IsNullOrEmpty(m.Question1Answer) ? 0 : Double.Parse(m.Question1Answer)).Average();
model.ServicePerformance = _result.Select(m => string.IsNullOrEmpty(m.Question2Answer) ? 0 : Double.Parse(m.Question2Answer)).Average();
model.InstallPerformance = _result.Select(m => string.IsNullOrEmpty(m.Question3Answer) ? 0 : Double.Parse(m.Question3Answer)).Average();
model.ReferringLennox = _result.Select(m => string.IsNullOrEmpty(m.Question4Answer) ? 0 : Double.Parse(m.Question4Answer)).Average();
}
and there are 5 additional model parameters and for each parameters, a new var _result and _SentSurveys are created..i just want to streamline this code.
I think refactoring this first can make writing these queries easier would be beneficial. If this isn't an option, you can use some CompiledQueries to cut down on the repetition of the big queries. But doing so doesn't make it "streamlined" in terms of efficiency, just makes your code slightly cleaner. Additionally, your post-processing in both cases look nearly identical with a lot of unnecessary checks. No need to repeat the common stuff. With some heavy refactoring, you could probably do something like this:
// need to set up the compiled queries first
static readonly Func<MyDataContextType,
MyModelType,
Func<MyDataContextType, MailingListEntry, MailingList, Channel, MyModelType, bool>,
IQueryable<LennoxSurveyResponse>>
GetResult = CompiledQuery.Compile(
(MyDataContextType ctx, MyModelType mod,
Func<MyDataContextType, MailingListEntry, MailingList, Channel, MyModelType, bool> pred) =>
from lsr in ctx.LennoxSurveyResponses
join mle in ctx.MailingListEntries on lsr.SurveyCode equals mle.SurveyCode
join ml in ctx.MailingLists on mle.MailingListId equals ml.MailingListId
join ch in ctx.Channels on ml.ChannelId equals ch.ChannelId
where pred(ctx, mod, mle, ml, ch)
select lsr);
static readonly Func<MyDataContextType, MyModelType, IQueryable<MailingListEntry>>
GetSentSurveys = CompiledQuery.Compile(
(MyDataContextType ctx, MyModelType mod) =>
from mle in ctx.MailingListEntries
join ml in ctx.MailingLists on mle.MailingListId equals ml.MailingListId
join ch in ctx.Channels on ml.ChannelId equals ch.ChannelId
where ch.ChannelId == mod.ChannelId
&& (mle.EmailDate != null || mle.LetterDate != null || mle.EmailBounce == null)
select mle);
static readonly Func<MyDataContextType, MyModelType, MailingListEntry, MailingList, Channel, bool>
ChannelPredicate = CompiledQuery.Compile(
(MyDataContextType ctx, MyModelType mod,
MailingListEntry mle, MailingList ml, Channel ch) =>
ch.ChannelId == mod.ChannelId && ml.EmailBounce == null || !ml.EmailBounce.Value);
static readonly Func<MyDataContextType, MyModelType, MailingListEntry, MailingList, Channel, bool>
TMPredicate = CompiledQuery.Compile(
(MyDataContextType ctx, MyModelType mod,
MailingListEntry mle, MailingList ml, Channel ch) =>
ch.ChannelGroupId == mod.TMId);
static void UpdateModel(MyModelType model)
{
if (model.ChannelId == 0 && model.TMId == 0) return;
var currentContext = SessionHandler.CurrentContext;
var predicate = (model.ChannelId != 0) ? ChannelPredicate : TMPredicate;
var results = GetResults(currentContext, model, predicate).ToList();
var sentSurveys = GetSentSurveys(currentContext, model).ToList();
model.SentSurveys = sentSurveys.Count();
model.CompletedSurveys = results.Count();
model.PercentageComplete = model.SentSurveys != 0 ? model.CompletedSurveys / model.SentSurveys : 0;
model.Referring = _result.Average(m => string.IsNullOrEmpty(m.Question1Answer) ? 0 : Double.Parse(m.Question1Answer));
model.ServicePerformance = _result.Average(m => string.IsNullOrEmpty(m.Question2Answer) ? 0 : Double.Parse(m.Question2Answer));
model.InstallPerformance = _result.Average(m => string.IsNullOrEmpty(m.Question3Answer) ? 0 : Double.Parse(m.Question3Answer));
model.ReferringLennox = _result.Average(m => string.IsNullOrEmpty(m.Question4Answer) ? 0 : Double.Parse(m.Question4Answer));
if (model.ChannelId != 0)
{
// should be rounded
model.Referring = Math.Round(model.Referring);
model.ServicePerformance = Math.Round(model.ServicePerformance);
model.InstallPerformance = Math.Round(model.InstallPerformance);
model.ReferringLennox = Math.Round(model.ReferringLennox);
}
}

Categories