How to combine 2 linq statments with groupby clause into 1 - c#

I was wondering if i can consolidate below 2 linq statments into 1 statment. I am sure it should be possible, but various attempts i am unable to manage.
var prevProvisionsBySubBook = (from provision in prevProvisions
group provision by provision.SubBook
into subBookGrouping
select
new
{
Key = subBookGrouping.Key,
Value = subBookGrouping.Sum(t => t.ProvisionUSD)
});
var currentProvisionsBySubBook
= (from provision in currentProvisions
group provision by provision.SubBook
into subBookGrouping
select new
{
Key = subBookGrouping.Key,
Value = subBookGrouping.Sum(t => t.ProvisionUSD)
});
var adjustmentChangeBySubBook
= (from current in currentProvisionsBySubBook
select new
{
Key = current.Key,
Value = current.Value
- (prevProvisionsBySubBook.Any() ? prevProvisionsBySubBook.Where(t => t.Key == current.Key).Single().Value : 0)
});
any help would be apprecaited.

You can do it like this:
var adjustmentChangeBySubBook =
from provision in
(from currentProvision in currentProvisions select new
{
currentProvision.SubBook,
CurrentUSD = currentProvision.ProvisionUSD,
PreviousUSD = 0
}).Concat
(from prevProvision in prevProvisions select new
{
prevProvision.SubBook,
CurrentUSD = 0,
PreviousUSD = prevProvision.ProvisionUSD
})
group provision by provision.SubBook into subBookGrouping select new
{
subBookGrouping.Key,
Value = subBookGrouping.Sum(t => t.CurrentUSD - t.PreviousUSD)
};

Related

Code Coming up blank every time

I have this code and it is supposed to fill up the appropriate tables and it is filling the first table (Mu_Reports) one but the second table (MU_By_Machine) keeps coming up blank
using (var db = new ProductionContext())
{
var objct = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
objct.ExecuteStoreCommand("TRUNCATE TABLE [MU Report]");
objct.ExecuteStoreCommand("TRUNCATE TABLE [MU By Machine]");
db.SaveChanges();
var query = db.Production_Reports
.GroupBy(x => new { x.Date, x.Machine_Number, x.Shift })
.Select(x => new
{
Date = x.Key.Date,
Shift = x.Key.Shift,
MachineNum = x.Key.Machine_Number,
MU = x.Sum(i => i.Partial_MU_ * 100)
}).ToList();
foreach (var item in query)
{
var z = new MU_Report();
z.Date = System.Convert.ToDateTime(item.Date);
z.Shift = item.Shift;
z.Machine_Number = item.MachineNum;
z.MU = item.MU;
db.MU_Reports.Add(z);
db.SaveChanges();
}
var query2 = from b in db.MU_Reports
join downtime in db.Downtime_Reports on b.Shift equals downtime.Shift
where downtime.Downtime_Code.Equals("9185")
group downtime by new { b.Date, b.Shift, b.Machine_Number, b.MU } into g
select new
{
Date = g.Key.Date,
Shift = g.Key.Shift,
Machine = g.Key.Machine_Number,
MU = g.Key.MU,
No_Work_Hours = g.Sum(x => x.Total_DownTime)
};
foreach (var item in query2)
{
var y = new MU_By_Machine();
y.Date = item.Date;
y.Shift = item.Shift;
y.Machine_Number = item.Machine;
y.MU = item.MU;
y.MU_w_o_No_Work = (item.MU * 8) / (8 - item.No_Work_Hours);
db.MU_By_Machines.Add(y);
db.SaveChanges();
}
}
I don't know if it is because I cannot have query and query2 go in the same button or if I am just doing something wrong. No error occurs only MU_By_Machine appears blank. Please keep in mind I'm new to C#.
You will need to invoke .ToList() at the end of your select statement in query2 as well.

LINQ pivot top 5 rows to columns

The desired output is a set of rows containing details about a physician and the top 5 procedures they performed (by volume) that are not in our benchmarking tables - with a minimum of one per month. Even with my limited LINQ experience, I have managed to get this working, but the performance in abysmal. In the spirit of becoming better at LINQ, I thought I'd see if there was a better way to approach this (besides coding in SQL).
Here is the entire method, although I believe it is the final statement (var report =) that deserves the most attention.
//Get the Providers for the selected AccessLevel & Report Period
var providerRiskLevels = GetProviderRiskLevelForAccessLevel(userAccessLevelId, reportPeriodId, providerNamePiece);
short benchmarkYear = (
from rp in db.ReportPeriods
where rp.ReportPeriodId == reportPeriodId
select rp.BenchmarkDataYear
).FirstOrDefault();
byte Duration = (
from rp in db.ReportPeriods
where rp.ReportPeriodId == reportPeriodId
select rp.Duration
).FirstOrDefault();
//Summarize counts by procedure code (ignoring modifiers)
var codeCounts =
from pp in db.ProviderProductions
//332 - restrict to valid codes
join pc in db.ProcedureCodes on pp.ProcedureCode equals pc.ProcedureCode1
where pp.ReportPeriodId == reportPeriodId
//show deleted codes as potential issue
&& pc.TerminatedDate == null
&& (codeFilter == null || pp.ProcedureCode == codeFilter)
join pc in db.PspsProcedures
on new { col1 = pp.ProcedureCode, col2 = benchmarkYear } equals new { col1 = pc.ProcedureCode, col2 = pc.Year } into left
from l_d in left.DefaultIfEmpty()
where l_d == null
group pp by
new { pp.ProviderId, pp.ProcedureCode }
into g
orderby g.Key.ProviderId, g.Sum(x => x.Volume) descending
where g.Sum(x => x.Volume) > Duration
select new NewCodesEntity
{
ProviderId = g.Key.ProviderId,
ProcedureCode = g.Key.ProcedureCode,
Volume = g.Sum(x => x.Volume)
};
//Get top 5 procedures performed by provider
var newCodes =
from cc in codeCounts
group cc by
new { cc.ProviderId }
into g
select new ProviderNewCodesEntity
{
ProviderId = g.Key.ProviderId,
Codes = g.OrderByDescending(x => x.Volume).Take(5).ToList()
};
//Build the report
var report =
from pr in providerRiskLevels
join nc in newCodes on pr.Provider.ProviderId equals nc.ProviderId
where pr.RiskCategoryId == RiskCategoryIds.VisibleRisk
&& (filterRiskLevelNums.Contains(pr.RiskLevelNum))
&& (filterSpecialtyId == 0 || pr.Provider.Specialty.SpecialtyId == filterSpecialtyId)
select new ProbeAuditEntity
{
ProviderId = pr.Provider.ProviderId,
ProviderName = pr.Provider.Name,
ProviderCode = pr.Provider.ProviderCode,
SpecialtyName = pr.Provider.Specialty.Name,
SpecialtyCode = pr.Provider.Specialty.SpecialtyCode,
VisibleRisk = pr.RiskScore,
NewCode1 = nc.Codes.OrderByDescending(c => c.Volume).FirstOrDefault().ProcedureCode,
NewCode2 = nc.Codes.OrderByDescending(c => c.Volume).Skip(1).FirstOrDefault().ProcedureCode,
NewCode3 = nc.Codes.OrderByDescending(c => c.Volume).Skip(2).FirstOrDefault().ProcedureCode,
NewCode4 = nc.Codes.OrderByDescending(c => c.Volume).Skip(3).FirstOrDefault().ProcedureCode,
NewCode5 = nc.Codes.OrderByDescending(c => c.Volume).Skip(4).FirstOrDefault().ProcedureCode
};
return report;
I appreciate your suggestions.
Give this a try for the report:
//Build the report
var report =
(from pr in providerRiskLevels
join nc in newCodes on pr.Provider.ProviderId equals nc.ProviderId
where pr.RiskCategoryId == RiskCategoryIds.VisibleRisk
&& filterRiskLevelNums.Contains(pr.RiskLevelNum)
&& (filterSpecialtyId == 0
|| pr.Provider.Specialty.SpecialtyId == filterSpecialtyId)
select new
{
RiskLevel = pr,
NewCodes = nc.Codes.OrderByDescending(c => c.Volumn).Select(c => c.ProcedureCode).Take(5)
})
.AsEnumerable()
.Select(x => new ProbeAuditEntity
{
ProviderId = x.RiskLevel.Provider.ProviderId,
ProviderName = x.RiskLevel.Provider.Name,
ProviderCode = x.RiskLevel.Provider.ProviderCode,
SpecialtyName = x.RiskLevel.Provider.Specialty.Name,
SpecialtyCode = x.RiskLevel.Provider.Specialty.SpecialtyCode,
VisibleRisk = x.RiskLevel.RiskScore,
NewCodes = x.NewCodes.Concat(Enumerable.Repeat(<DefaultProcedureCodeHere>, 5)).Take(5)
});
Or, if ProbeAuditEntity is a class you could do this:
//Build the report
var report =
(from pr in providerRiskLevels
join nc in newCodes on pr.Provider.ProviderId equals nc.ProviderId
where pr.RiskCategoryId == RiskCategoryIds.VisibleRisk
&& filterRiskLevelNums.Contains(pr.RiskLevelNum)
&& (filterSpecialtyId == 0
|| pr.Provider.Specialty.SpecialtyId == filterSpecialtyId)
select new ProbeAuditEntity
{
ProviderId = x.RiskLevel.Provider.ProviderId,
ProviderName = x.RiskLevel.Provider.Name,
ProviderCode = x.RiskLevel.Provider.ProviderCode,
SpecialtyName = x.RiskLevel.Provider.Specialty.Name,
SpecialtyCode = x.RiskLevel.Provider.Specialty.SpecialtyCode,
VisibleRisk = x.RiskLevel.RiskScore,
NewCodes = nc.Codes.OrderByDescending(c => c.Volumn).Select(c => c.ProcedureCode).Take(5)
})
.ToList();
report
.ForEach(x => x.NewCodes = x.NewCodes.Concat(Enumerable.Repeat(<DefaultProcedureCodeHere>, 5)).Take(5);

Get parameters outside of Grouping Linq

I need to get some Field's out of the Group using linq for example, this is my code:
(from PaymentTypes in PaymentTypes_DataTable.AsEnumerable()
join CashTransactions in CashTransactions_DataTable.AsEnumerable()
on PaymentTypes.Field<Int32>("cashpaymenttype_id")
equals CashTransactions.Field<Int32>("cashpaymenttype_id")
into JoinedCashTransactions
from CashTransactions in JoinedCashTransactions.DefaultIfEmpty()
group CashTransactions by PaymentTypes.Field<Int32>("cashpaymenttype_id")
into GroupPaymentTypes
select new
{
cashpaymenttype_id = 0, // Get PaymentTypeID
cashpaymenttype_name = "", // Get PaymentTypeName
cashtransaction_amount = GroupPaymentTypes.Sum(a =>
a != null
? (a.Field<Int32>("cashtransactionstatus_id") == 1 ||
a.Field<Int32>("cashtransactionstatus_id") == 3 ? 1 : -1) *
a.Field<Double>("cashtransaction_amount")
: 0.00),
}).Aggregate(PaymentTypesTransactions_DataTable, (dt, result) => {
dt.Rows.Add(result.cashpaymenttype_id, result.cashpaymenttype_name,
result.cashtransaction_amount); return dt; });
This linq works but i need to get the fields cashpaymenttype_id and cashpaymenttype_name they are within PaymentTypes
Assuming PaymentTypeID - PaymentTypeName is 1-to-1, you could change your group by to this:
group CashTransactions by new
{
PaymentTypeId = PaymentTypes.Field<Int32>("cashpaymenttype_id"),
PaymentTypeName = PaymentTypes.Field<String>("cashpaymenttype_name")
}
into GroupPaymentTypes
The your select will look like this:
select new
{
cashpaymenttype_id = GroupPaymentTypes.Key.PaymentTypeId,
cashpaymenttype_name = GroupPaymentTypes.Key.PaymentTypeName,
...
}

Not getting the difference between two list by using linq

I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.
Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();

C# Linq Average

I have a table with data similar to below:
Group TimePoint Value
1 0 1
1 0 2
1 0 3
1 1 3
1 1 5
I want to project a table as such:
Group TimePoint AverageValue
1 0 2
1 1 4
EDIT: The data is in a datatable.
Anybody any ideas how this can be done with LINQ or otherwise?
Thanks.
You need to perform Group By
The linq you need is something like:
var query = from item in inputTable
group item by new { Group = item.Group, TimePoint = item.TimePoint } into grouped
select new
{
Group = grouped.Key.Group,
TimePoint = grouped.Key.TimePoint,
AverageValue = grouped.Average(x => x.Value)
} ;
For more Linq samples, I highly recommend the 101 Linq samples page - http://msdn.microsoft.com/en-us/vcsharp/aa336747#avgGrouped
Here's a more function-oriented approach (the way I prefer it). The first line won't compile, so fill it in with your data instead.
var items = new[] { new { Group = 1, TimePoint = 0, Value = 1} ... };
var answer = items.GroupBy(x => new { TimePoint = x.TimePoint, Group = x.Group })
.Select(x => new {
Group = x.Key.Group,
TimePoint = x.Key.TimePoint,
AverageValue = x.Average(y => y.Value),
}
);
You can do:
IEnumerable<MyClass> table = ...
var query = from item in table
group item by new { item.Group, item.TimePoint } into g
select new
{
g.Key.Group,
g.Key.TimePoint,
AverageValue = g.Average(i => i.Value)
};
Assuming a class like this:
public class Record
{
public int Group {get;set;}
public int TimePoint {get;set;}
public int Value {get;set;}
}
var groupAverage = from r in records
group r by new { r.Group, r.TimePoint } into groups
select new
{
Group = groups.Key.Group,
TimePoint = groups.Key.TimePoint,
AverageValue = groups.Average(rec => rec.Value)
};

Categories