I want to order my Linq GroupBy statement but the item that has the more Total Descending but i can't make it
This is my LinQ
foreach (var item in db
.Pos.Where(r => r.Fecha.Day <= today.Day)
.Select(g => new { Pdv = g.Pdv, Total = g.Total })
.GroupBy(l => l.Pdv)
.AsEnumerable()
.Select(z => new {
Punto_De_Venta=z.Key,
Total = String.Format("{0:$#,##0.00;($#,##0.00);Zero}",
Decimal.Round(z.Sum(l => l.Total), 0))
}))
{
listadepuntos.Add(item.ToString());
}
var grupoPdv = new SelectList(listadepuntos.ToList());
ViewBag.GroupS = grupoPdv;
The Out put of my Linq Statement is :
Punto_De_Venta = Central, Total = 42,143.00
Punto_De_Venta = Restaurante, Total = 189,949.00
Punto_De_Venta = Venta Moto, Total = 89,678.00
And the Output im looking for is:
Punto_De_Venta = Restaurante, Total = 189,949.00
Punto_De_Venta = Venta Moto, Total = 89,678.00
Punto_De_Venta = Central, Total = 42,143.00
How can i do this?? i cant find a way to make this
The List<> does guarantee ordering, sort the List before passing to your SelectList
var grupoPdv = new SelectList(listadepuntos.OrderByDescending(l=>l.Total).ToList());
ViewBag.GroupS = grupoPdv;
Another approach :
Modify source query to return a sorted list.
var results = db.Pos.Where(r => r.Fecha.Day <= today.Day)
.Select(g => new { Pdv = g.Pdv, Total = g.Total })
.GroupBy(l => l.Pdv).AsEnumerable()
.Select(z => new { Punto_De_Venta=z.Key, Total = String.Format("{0:$#,##0.00;($#,##0.00);Zero}", Decimal.Round(z.Sum(l => Total), 0))})
.OrderByDescending(l=>l.Total)
.ToList();
Once you get the sorted list you can create your SelectList with sorted result.
var grupoPdv = new SelectList(result);
ViewBag.GroupS = grupoPdv;
You'll need to do something like this:
foreach (var item in db.Pos.Where(r => r.Fecha.Day <= today.Day)
.Select(g => new { Pdv = g.Pdv, Total = g.Total })
.GroupBy(l => l.Pdv)
.AsEnumerable()
.Select(z => new { Punto_De_Venta = z.Key, Total = z.Sum(l => l.Total) })
.OrderByDescending(r => r.Total)
.Select(r => new { Punto_De_Venta = r.Punto_De_Venta, Total = String.Format("{0:$#,##0.00;($#,##0.00);Zero}", Decimal.Round(z.Sum(l => l.Total), 0))})
{
listadepuntos.Add(item.ToString());
}
Related
I have a Linq query written in C#. I don't know how to change it so that it works with UiPath.
The query finds all AccountNumber in the table and finds the sum of Remainder rows
var afterChange = listDate.GroupBy(account => account.AccountNumber)
.Select(group => new
{
AccountNumber = group.Key,
Сurrency = group.Select(groupElement => groupElement.Сurrency).First(),
Remainder = group.Select(groupElement => groupElement.Remainder).Sum(),
})
.AsEnumerable()
.Select(x => new TableData
{
Remainder = x.Remainder,
AccountNumber = x.AccountNumber,
Сurrency = x.Сurrency
})
.ToList();
Not familiar with UiPath, but your query needs correction.
var afterChange = listDate.GroupBy(account => new { account.AccountNumber, account.Сurrency })
.Select(group => new TableData
{
AccountNumber = group.Key.AccountNumber,
Сurrency = group.Key.Сurrency,
Remainder = group.Sum(x => x.Remainder),
})
.ToList();
Is there a way to check if the sum of PREM_A or PREM_B is not 0 in the same LINQ query and not in a separate LINQ query like the one below i.e. matchRows?
var resultsDt = dt.AsEnumerable().GroupBy(row => new
{
Id = row.Field<string>("ID")
}).Select(grp =>
{
DataRow newRow = dt.NewRow();
newRow["ID"] = grp.Key.Id.Trim();
newRow["PREM_A"] = grp.Sum(r => r.Field<decimal>("PREM_A"));
newRow["PREM_B"] = grp.Sum(r => r.Field<decimal>("PREM_B"));
return newRow;
}).CopyToDataTable();
var matchRows = resultsDt.Select().Where(x => x.Field<decimal>("PREM_A") != 0 || x.Field<decimal>("PREM_B") != 0);
foreach (DataRow row in matchRows)
{
//do something
}
You don't need to convert to a data table for every step, it would be easier to query if you moved away from that.
var query =
from row in dt.AsEnumerable()
group new
{
premA = row.Field<decimal>("PREM_A"),
premB = row.Field<decimal>("PREM_B"),
} by row.Field<string>("ID").Trim() into g
let premA = g.Sum(x => x.premA)
let premB = g.Sum(x => x.premB)
where premA != 0M || premB != 0M
select new
{
Id = g.Key,
PremA = premA,
PremB = premB,
};
Also:
var resultsDt = dt.AsEnumerable()
.GroupBy(row => row.Field<string>("ID"))
.Select(grp =>new {Id= grp.Key,
PREM_A= grp.Sum(r => r.Field<decimal>("PREM_A")),
PREM_B=grp.Sum(r => r.Field<decimal>("PREM_B"))
})
.Where(e=>e.PREM_A!=0 || e.PREM_B!=0);
I want add a new column to find which is lasted record in group.
Can I write subquery in Select() method?
I have try this
var test = DailyPeriods.Where(x => x.BookingDate == "2016/12/30")
.Select(x =>
new
{
PERIOD_GROUP_ID = x.PeriodGroupID,
PERIOD_NAME = x.PeriodName,
New_Column = DailyPeriods
.Where(z => z.BookingDate == "2016/12/30")
.Select(a =>
new
{
PeriodGroupID = a.PeriodGroupID,
period_name = a.PeriodName
}
)
.GroupBy(b => b.period_name)
.Select(g => g.Last().PeriodGroupID)
.Contains(x.PeriodName)
})
But will occur this error
"column not in scope: A:2211708.C(BOOKING_DATE)"
Try this..
var lastRecords = periodList.GroupBy(l => l.PeriodName)
.Select(x => new { PeriodName = x.Key,
PeriodGroupId = x.OrderBy(l => l.PeriodGroupId).Last().PeriodGroupId});
var result = from period in periodList
from lastRec in lastRecords.Where(r => r.PeriodGroupId == period.PeriodGroupId
&& r.PeriodName == period.PeriodName)
.DefaultIfEmpty()
select new { period.PeriodGroupId,period.PeriodName, New_Column=lastRec==null?false:true };
I'm trying to translate a query I've written to Linq for the past few days I can't seem to make it work. This is the query I'm trying to translate:
SELECT
hsd.CoveragePeriodBeginDate,
RateTotal = SUM(hsd.Rate),
ReimbursementTotal = SUM(hsd.TotalReimbursement),
AdjustmentsTotal = SUM(hsd.Adjustments)
FROM
( SELECT
CoveragePeriodBeginDate,
PaidDate,
Rate = TotalClaimCharge,
TotalReimbursement = ReimbursementAmount,
Adjustments = SUM(BaseRateChangeAmount)
FROM
dbo.HsdMonthlyCapitatation
WHERE
MemberID = 12345678
GROUP BY
CoveragePeriodBeginDate,
PaidDate,
TotalClaimCharge,
ReimbursementAmount
) hsd
GROUP BY
hsd.CoveragePeriodBeginDate
ORDER BY
hsd.CoveragePeriodBeginDate
What I need to do is translate this into Linq. I have tried many different ways, but can't seem to make it work right. It always seems to aggregate too much.
Here's the closest I've come.
var rawCapData = db.HsdMonthlyCapitations.Where(x => x.MemberID == memberID)
.Select(x => new {
CoveragePeriod = x.CoveragePeriodBeginDate,
TotalCharge = x.TotalClaimCharge,
Reimbursement = x.ReimbursementAmount,
PaidDate = x.PaidDate,
Adjust = x.BaseRateChangeAmount
})
.GroupBy(x => new {
CoverageDate = x.CoveragePeriod,
Paid = x.PaidDate,
Rate = x.TotalCharge,
Reimburse = x.Reimbursement
})
.GroupBy(x => new {
Coverage = x.Key.CoverageDate,
DhsRate = x.Sum(y => y.TotalCharge),
ReimbursementTotal = x.Sum(y => y.Reimbursement),
Adjustments = x.Sum(y => y.Adjust)
})
.Select(x => new {
CapMonthYear = x.Key.Coverage,
DhsRate = x.Key.DhsRate,
TotalReimbursement = x.Key.ReimbursementTotal,
AdjustmentsTotal = x.Key.Adjustments
});
I should say I have gotten it to work, but I feel it's rather cludgey and a mix of regular LINQ and lambda expressions, and I would prefer to code it all with lambda expressions, if at all possible. Here's the code I have gotten to work:
var rawCapitationData = from capitation
in db.HsdMonthlyCapitations
where capitation.MemberID == memberID
group capitation by new
{
capitation.CoveragePeriodBeginDate,
capitation.TotalClaimCharge,
capitation.ReimbursementAmount,
capitation.PaidDate
} into cap
select new {
CapitationMonthYear = cap.Key.CoveragePeriodBeginDate,
TotalReimbursement = cap.Key.TotalClaimCharge,
DhsCapitationAmount = cap.Key.ReimbursementAmount,
PaidDate = cap.Key.PaidDate,
DhsAdjustments = cap.Sum(x => x.BaseRateChangeAmount)
};
var capitationData = rawCapitationData.GroupBy(cap => cap.CapitationMonthYear)
.Select(data => new {
CapitationDate = data.Key,
TotalReimbursement = data.Sum(x => x.TotalReimbursement),
DhsCapitationAmount = data.Sum(x => x.DhsCapitationAmount),
DhsAdjustments = data.Sum(x => x.DhsAdjustments)
});
My preference is to do this all in one statement. Is it even possible? I feel I'm close with the lambda expressions, but I know I'm missing something.
Any help or advice is greatly appreciated.
Not sure what are you trying to achieve, but I've ended up with this:
return db.HsdMonthlyCapitations
.Where(x => x.MemberID == memberID)
.GroupBy(x => new {x.CoveragePeriodBeginDate, x.PaidDate, x.TotalClaimCharge, x.ReimbursementAmount})
.Select(x => new
{
x.Key.CoveragePeriodBeginDate,
x.Key.PaidDate,
Rate = x.Key.TotalClaimCharge,
TotalReimbursement = x.Key.ReimbursementAmount,
Adjustments = x.Sum(m => m.BaseRateChangeAmount)
})
.GroupBy(x => x.CoveragePeriodBeginDate)
.Select(x => new
{
CoveragePeriodBeginDate = x.Key,
RateTotal = x.Sum(m => m.Rate),
ReimbursementTotal = x.Sum(m => m.TotalReimbursement),
AdjustmentsTotal = x.Sum(m => m.Adjustments),
})
.OrderBy(x => x.CoveragePeriodBeginDate);
I have a simple list
var list =
AppUtils.db.GetDataTable("dbo.RankSelectChart", view) // stopred procedure and getting datatable
.AsEnumerable()
.Select(i => new
{
Date = i.Field<DateTime>("lastDatetime"),
P1 = i.Field<decimal>("p1"),
P2 = i.Field<decimal>("P2"),
P3..... P(n)
}
)
.ToList()
.OrderBy(x => x.Date);
than i want to get a list of lists or dictionary like List<Dictionary<Datetime, Decimal>> means Dictionary<Date, P1> .... Dictionary<Date, P(n)>
how to write algorithm which is not depend how many P we have
As it stands, you will need to use reflection to access the properties:
var result = new[]{"P1", "P2", "P3", ...}.Select(p => list.ToDictionary(
i => i.Date,
i => i.GetType().GetProperty(p).GetValue(i)));
However, if you could avoid creating your list in the first place and just pull from the data table directly, it may be easier.
var dt = AppUtils.db.GetDataTable("dbo.RankSelectChart", view); // stopred procedure and getting datatable
var pColumns = dt.Columns.Cast<DataColumn>()
.Where(c => c.ColumnName.StartsWith("p"));
var result = pColumns
.Select(p => dt.AsEnumerable().ToDictionary(
i => i.Field<DateTime>("lastDatetime"),
i => i.Field<DateTime>(p.ColumnName)))
.ToList();
If 'Date' is unique for all records in 'list', then you can use reflection to get the P(i) value for a record in list. Like so:
// build sample data
var list = Enumerable.Range(0, 10)
.ToList()
.Select(x => new {
Date = DateTime.Now.AddMinutes(x),
P1 = new Decimal(x),
P2 = new Decimal(x + 1),
P3 = new Decimal(x + 2)
})
.ToList();
// list partionned by date; assumes that Date is unique in list
List<Dictionary<DateTime, Decimal>> partitionedList;
if (list.Count == 0) {
partitionedList = new List<Dictionary<DateTime, Decimal>>();
} else {
var n = 3;
var listElementType = list[0].GetType();
partitionedList = Enumerable.Range(1, n)
.Select(x => {
var prop = listElementType.GetProperty("P" + x);
var pList = list.ToDictionary(
ll => ll.Date,
ll => (Decimal)prop.GetValue(ll));
return pList;
})
.ToList();
}
If 'Date' is not unique, then it cannot be the key to a dictionary and the desired data structure is not achievable.