I have the following code
var profilesWithMailLists = profilesWithCf.GroupJoin(
profile2Maillist,
p => p.SqlId,
p2l => p2l.ProfileId,
(p, mailLists) =>
{
var p2lmongo = mailLists.Select<TProfile2MailList, Profile2MailList>(p2l =>
{
return new Profile2MailList
{
MailListId = p2l.MailListId,
Status = p2l.Status,
SubscriptionDate = p2l.SubscriptionDate
};
});
p.MailLists = p2lmongo.ToArray();
return p;
});
Is it possible to skip iteration and returning of profile if p2lmongo collection will contain 0 elements ?
Try using GroupBy and a Join instead of GroupJoin.
Some code to illustrate (not tested or type-checked):
var profilesWithMailListsAlt =
profilesWithCf.Join(
profile2Maillist.GroupBy(p2l => p2l.ProfileId),
p => p.SqlId,
p2lgroup => p2lgroup.Key,
(p, mailListGroup) =>
{
var p2lmongo = mailListGroup.Select<TProfile2MailList, Profile2MailList>(p2l =>
{
return new Profile2MailList
{
MailListId = p2l.MailListId,
Status = p2l.Status,
SubscriptionDate = p2l.SubscriptionDate
};
});
p.MailLists = p2lmongo.ToArray();
return p;
});
If that still doesn't do what you want, try explicitly excluding empty groups by changing
profile2Maillist.GroupBy(p2l => p2l.ProfileId)
to
profile2Maillist.GroupBy(p2l => p2l.ProfileId).Where(group => group.Any())
Just shooting from the hip here.
Related
I have 2 almost identical linq queries and want to remove repeating code from it. The only difference is the extra property in the GroupBy depending on some true/false condition.
How can I conditionally group by in linq without repeating the code like below?
var allergensList = _context.RecipeAllergens
.Where(x => x.ParentId == Id && x.AllergenId != null)
.ToList();
var allergens = new List<AllergenInfo>();
if (isRecipe)
{
allergens = allergensList
.GroupBy(x => new { x.AllergenName, x.AllergenIcon, x.AllergenMaycontains })
.Select(a =>
{
var v = a.OrderBy(x => x.AllergenMaycontains).First();
return new AllergenInfo
{
AllergenName = v.AllergenName,
AllergenIcon = v.AllergenIcon,
AllergenMayContain = v.AllergenMaycontains ?? false
};
})
.ToList();
}
else
{
allergens = allergensList
.GroupBy(x => new { x.AllergenName, x.AllergenIcon })
.Select(a =>
{
var v = a.OrderBy(x => x.AllergenMaycontains).First();
return new AllergenInfo
{
AllergenName = v.AllergenName,
AllergenIcon = v.AllergenIcon,
AllergenMayContain = v.AllergenMaycontains ?? false
};
})
.ToList();
}
You can left grouping by x.AllergenMaycontains but under condition
allergens = allergensList
.GroupBy(x => new { x.AllergenName, x.AllergenIcon, AllergenMaycontains = isRecipe ? x.AllergenMaycontains : false })
.Select(a =>
{
var v = a.OrderBy(x => x.AllergenMaycontains).First();
return new AllergenInfo
{
AllergenName = v.AllergenName,
AllergenIcon = v.AllergenIcon,
AllergenMayContain = v.AllergenMaycontains ?? false
};
})
.ToList();
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 this Linq to Entity:
var sitesGrpByClientAndFreq = from cfr in clientFullReview2
group cfr by new { cfr.inspectionFreqvency } into g
select new
{
inspectionFreqvency = g.Key.inspectionFreqvency,
siteCount = g.Select(x => x.siteId).ToArray().Distinct().Count(),
normalSitesCount = g.Where(x => x.isNormal == true).Select(x=>x.isNormal).ToArray().Count(),
}
From the above linq I get this result:
My question is How can I remove all rows where inspectionFrequency = -1?
You can mix and match the let keyword with where. It could be something like:
var sitesGrpByClientAndFreq =
from cfr in clientFullReview2
group cfr by new { cfr.inspectionFreqvency } into g
let inspectionFreqvency = g.Key.inspectionFreqvency
where inspectionFreqvency != -1
select new
{
inspectionFreqvency = inspectionFreqvency,
siteCount = g.Select(x => x.siteId).ToArray().Distinct().Count(),
normalSitesCount = g.Where(x => x.isNormal == true).Select(x=>x.isNormal).ToArray().Count(),
}
I'm trying to translate this sql statement
SELECT row, SUM(value) as VarSum, AVG(value) as VarAve, COUNT(value) as TotalCount
FROM MDNumeric
WHERE collectionid = 6 and varname in ('C3INEV1', 'C3INEVA2', 'C3INEVA3', 'C3INVA11', 'C3INVA17', 'C3INVA19')
GROUP BY row
into an EF 4 query using lambda expressions and am missing something.
I have:
sumvars = sv.staticvararraylist.Split(',');
var aavresult = _myIFR.MDNumerics
.Where(r => r.collectionid == _collid)
.Where(r => sumvars.Contains(r.varname))
.GroupBy(r1 =>r1.row)
.Select(rg =>
new
{
Row = rg.Key,
VarSum = rg.Sum(p => p.value),
VarAve = rg.Average(p => p.value),
TotalCount = rg.Count()
});
where the staticvararraylist has the string 'C3INEV1', 'C3INEVA2', 'C3INEVA3', 'C3INVA11', 'C3INVA17', 'C3INVA19' (without single quotes) and the _collid variable = 6.
While I'm getting the correct grouping, my sum, average, & count values aren't correct.
You didn't post your error message, but I suspect it's related to Contains. I've found that Any works just as well.
This should get you quite close:
var result =
from i in _myIFR.MDNumerics
where i.collectionid == _collid && sumvars.Any(v => i.varname == v)
group i by i.row into g
select new {
row = g.Key,
VarSum = g.Sum(p => p.value),
VarAve = g.Average(p => p.value),
TotalCount = g.Count()
};
Try this:
var aavresult = _myIFR.MDNumerics
.Where(r => r.collectionid == _collid && sumvars.Contains(r.varname))
.GroupBy(r1 =>r1.row,
(key,res) => new
{
Row = key,
VarSum = res.Sum(r1 => r1.value),
VarAve = res.Average(r1 => r1.value),
TotalCount = res.Count()
});
I have this function:
/// <summary>
/// Return array of all badges for a users
/// </summary>
public static Badge[] getUserBadges(int UserID)
{
Badge[] ReturnBadges;
using (MainContext db = new MainContext())
{
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => c.BadgeID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c });
ReturnBadges = new Badge[q.Count()];
int i = 0;
foreach (var UserBadge in q)
{
ReturnBadges[i] = new Badge(UserBadge.TheBadge.Key);
ReturnBadges[i].Quantity = UserBadge.BadgeCount;
i++;
}
}
return ReturnBadges;
}
I wish to order by tblBadges.OrderID ascending but I can't seem to find out where to put it, can anyone help?
I've tried:
.OrderBy(c=> c.TheBadge.OrderID)
But it's not valid code. TheBadge.Key in the loop is a tblBadges type. It's confusing me a bit why intellisense wont let me do the order by anywhere!
TheBadge isn't a single badge, it's a group of badges... so I'd personally rename it if I were you. Now, which OrderId do you want to get? You've got multiple entities in the gruop. For example, you could do this:
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => c.BadgeID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c })
.OrderBy(x => x.TheBadge.First().OrderId);
That will order by some notional "first" element - although I don't know what the generated SQL will look like.
If you expect the OrderId to be the same for every badge with the same ID, you might use:
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => new { c.BadgeID, c.OrderID })
.OrderBy(group => group.Key.OrderID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c });
Try this:
var q = db.tblBadgeUsers
.Where(c => c.UserID == UserID)
.GroupBy(c => c.BadgeID)
.Select(c => new { BadgeCount = c.Count(), TheBadge = c.Key }) // *mod
.OrderBy(c=> c.TheBadge.OrderID); // * added
In the following line, TheBadge is a linq collection, not the badge itself. You want c.Key.
.Select(c => new { BadgeCount = c.Count(), TheBadge = c })