I am having trouble doing multiple counts on a single table in a LINQ query. I am using NHibernate, LINQ to NHibernate and C#.
query is a populated list. I have a table that has a boolean called FullRef. I want to do a LINQ query to give a count of occurances of FullRef = false and FullRef = true on each TrackId. TrackId gets a new row for each time he gets a track.Source == "UserRef".
In the following query I get the correct number count (from the FullRefTrueCount) of FullRef = true, but it gives an unknown wrong number on the FullRefFalseCount.
var query2 = from track in query
where track.Source == "UserRef"
group track by new { TrackId = track.TrackId, FullRef = track.FullRef } into d
select new FullReferrer
{
Customer = d.Key.TrackId,
FullRefFalseCount = d.Where(x => x.FullRef == false).Count(),
FullRefTrueCount = d.Where(x => x.FullRef == true).Count()
};
I also tried to modify it to not contain the FullRef in the group by. This was done by removing FullRef = track.FullRef on the by like this
var query2 = from track in query
where track.Source == "UserRef"
group track by new { TrackId = track.TrackId } into d
select new FullReferrer
{
Customer = d.Key.TrackId,
FullRefFalseCount = d.Where(x => x.FullRef == false).Count(),
FullRefTrueCount = d.Where(x => x.FullRef == true).Count()
};
Now it gives me the total count of TrackId, ignoring my .Where(x => x.FullRef == true/false) statement.
Anyone have any idea on how to fix it?
I guess it is the "group by" that is the problem. Can I somehow avoid doing a group by?
Do I maybe need a join?
For NHibernate I don't know, but using Linq With Entity Framework this should get what you want:
var query2 = (
from track in someDbSet
select new FullReferrer
{
Customer = track.trackId
, FullRefFalseCount = (from fullRefFalse in someDbSet.tracks
where fullRefFalse.IsSale == false
&& fullRefFalse.trackId == track.trackId
select fullRefFalse).Count()
, FullRefTrueCount = (from fullRefTrue in someDbSet.tracks
where fullRefTrue.IsSale == true
&& fullRefTrue.trackId == track.trackId
select fullRefTrue).Count()
}
).Distinct();
FullRefFalseCount = d.Where(x => x.FullRef == false).ToList().Count
FullRefTrueCount = d.Where(x => x.FullRef == true).ToList().Count
try this
Try out Count(condition).
FullRefFalseCount = d.Count(x => x.FullRef == false),
FullRefTrueCount = d.Count(x => x.FullRef == true)
try this. This takes the expected data from data table.
string source = "UserRef";
var result = from row in dt.AsEnumerable()
where row["source"].Equals(source)
group row by row["TrackId"]
into g
select new
{
TrackId = g.Key,
FullRefTrueCount = ((from track in g where track["FullRef"].Equals("true") select track).Count()),
FullRefFalseCount = ((from track in g where track["FullRef"].Equals("false") select track).Count())
};
To anyone else having a similar problem I solved it by making it ".AsEnumerable()"
var query2 = from track in query.AsEnumerable() // <--- the solution
where track.Source == "UserRef"
group track by new { TrackId = track.TrackId } into d
select new FullReferrer
{
Customer = d.Key.TrackId,
FullRefFalseCount = d.Count(x => !x.FullRef),
FullRefTrueCount = d.Count(x => !x.FullRef)
};
Related
I want to display how many transfers did every customer.
I want to display CustomerId, Name and Totaly amount of transfers.
I mean I want to display CustomerId too, not only Name and Amount transfers.
Everything works fine except CustomerId: it is empty in my DataGridview.
I don't know how to do and I would really appreciate any kind of help.
Here is my code:
using (Db db = new Db())
{
var statistic = (from u in db.Transfers
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.IsActive == true && u.Paid == true
group u by c.FirstName into g
select new
{
// here I get Headertext but not Id's value
Id = g.Select(x =>x.CustomerId),
Name = g.Key,
Totaly = g.Sum(x => x.Amount)
}).OrderByDescending(x => x.Totaly).ToList();
if (statistic != null)
{
dgvCustomerList.DataSource = statistic;
}
}
The correct way is to group it by CustomerId (because CustomerId is unique, you will get distinct customers inside select and then you can use FirstOrDefault() for getting FirstName property):
using (Db db = new Db())
{
var statistic = (from u in db.Transfers
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.IsActive == true && u.Paid == true
group u by c.CustomerId into g
select new
{
Id = g.Key, // here I get Headertext but not Id's value
Name = g.FirstOrDefault().FirstName,
Totaly = g.Sum(x => x.Amount)
}).OrderByDescending(x => x.Totaly).ToList();
if (statistic != null)
{
dgvCustomerList.DataSource = statistic;
}
}
You can group by both customerId and FirstName
using (Db db = new Db())
{
var statistic = (from u in db.Transfers
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.IsActive == true && u.Paid == true
group u by new {key c.FirstName,key c.CustumerId} into g
select new
{
Id = g.Key.CustumerId,//g.Select(x =>x.CustomerId), // here I get Headertext but not Id's value
Name = g.Key.FirstName,
Totaly = g.Sum(x => x.Amount)
}).OrderByDescending(x => x.Totaly).ToList();
if (statistic != null)
{
dgvCustomerList.DataSource = statistic;
}
}
Can you please help to convert this from sql to linq, i am new to linq and been trying this and couldn't succeed. Let me know if this is even possible or not?
SELECT max(Products.ProductID) as ProductID, Products.SKU, Products.Name, Products.RRP, Products.Price,
max(Products.FrontTall) as FrontTall,
ProductsCategory.SortOrder,
Products.ColorValue,
max(Products.ColorImg) as ColorImg,
Products.IsPrimary,
Products.Visible
FROM Products INNER JOIN ProductsCategory ON Products.ProductID = ProductsCategory.ProductID
WHERE (ProductsCategory.CategoryID = 5 ) AND (Products.Visible = 1) AND (Products.Inactive = 0) AND (Products.Deleted = 0 or Products.Deleted is null)
GROUP BY SKU, Products.Name, RRP, Price, ColorValue, ProductsCategory.SortOrder, IsPrimary, Visible
AND this is what i am trying
var products = (from p in db.Products
join cp in db.ProductsCategories on p.ProductID equals cp.ProductID
where cp.CategoryID == catId && p.Visible == true && p.Inactive == false && (p.Deleted == null || p.Deleted == false)
group p by new {
p.SKU,
p.Name,
p.RRP,
p.Price,
p.ColorValue,
p.IsPrimary,
p.Visible,
cp.SortOrder
} into grouped
select new {
ProductID,
FrontTall,
ColorImg,
SKU = grouped.Key.SKU,
Name = grouped.Key.Name,
RRP = grouped.Key.RRP,
Price = grouped.Key.Price,
ColorValue = grouped.Key.ColorValue,
IsPrimary = grouped.Key.IsPrimary,
Visible = grouped.Key.Visible,
SortOrder = grouped.Key.SortOrder
})
.OrderBy(x => x.SortOrder);
I need to get the ProductID, FrontTall and ColorImg field value without including in group by
Thanks in advance.
Kish
select new {ProductID = grouped.Max(x => x.ProductID)}
I have this sql query that does exactly what i want but i need it in linq. It returns a few AVC rows and counts how many PersonAVCPermission that has status 1 linked to it
SELECT a.Id, a.Name, a.Address, COUNT(p.AVCID) AS Count
FROM AVC AS a
LEFT OUTER JOIN
(
SELECT PersonAVCPermission.AVCId
FROM PersonAVCPermission
WHERE PersonAVCPermission.Status = 1
) AS p
ON a.Id = p.AVCId
GROUP BY a.Id, a.Name, a.Address
I have this query in linq and it does the same thing except when there are no PersonAVCPermission it still counts 1
var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);
var q = from a in odc.AVCs
from p in yellows.Where(o => o.AVCId == a.Id).DefaultIfEmpty()
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
Id = agroup.Key.Id,
Name = agroup.Key.Name,
Address = agroup.Key.Address,
Count = agroup.Count(o => o.Id != null)
};
Im guessing that with DefaultIfEmpty() it places null rows in the list that then gets counted so i try to exclude them with (o => o.Id != null) but it still counts everything as at least one
If i dont use DefaultIfEmpty() it skips the rows with count 0 completely
How can i exclude them or am i doing it completely wrong?
How about using .Any() and a Let?
var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);
var q = from a in odc.AVCs
let Y = (from p in yellows.Where(o => o.AVCId == a.Id) select p).Any()
where Y == true
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
Id = agroup.Key.Id,
Name = agroup.Key.Name,
Address = agroup.Key.Address,
Count = agroup.Count(o => o.Id != null)
};
You don't need the join, nor the grouping:
var q = from a in odc.AVCs
select new AVCListItem
{
Id = a.Id,
Name = a.Name,
Address = a.Address,
Count = yellows.Where(o => o.AVCId == a.Id).Count()
};
I am getting data from multiple tables by joining and i want to group data on particular column value but after group by statement i can access my aliases and their properties. What mistake i am making?
public List<PatientHistory> GetPatientHistory(long prid)
{
using(var db = new bc_limsEntities())
{
List<PatientHistory> result =
(from r in db.dc_tresult
join t in db.dc_tp_test on r.testid equals t.TestId into x
from t in x.DefaultIfEmpty()
join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
from a in y.DefaultIfEmpty()
where r.prid == prid
group new {r,t,a} by new {r.testid} into g
select new PatientHistory
{
resultid = r.resultid,
bookingid = r.bookingid,
testid = r.testid,
prid = r.prid,
attributeid = r.attributeid,
result = r.result,
Test_Name = t.Test_Name,
Attribute_Name = a.Attribute_Name,
enteredon = r.enteredon,
Attribute_Type = a.Attribute_Type
}).ToList();
return result;
}
}
You're doing this wrong way. As been said by Jon after grouping the sequences with aliases r,t,a doesn't exist. After grouping you receive the sequence g with sequances of r,t,a in each element of g. If you want get one object from each group (for example most recent) you should try this:
List<PatientHistory> result =
(from r in db.dc_tresult
join t in db.dc_tp_test on r.testid equals t.TestId into x
from t in x.DefaultIfEmpty()
join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
from a in y.DefaultIfEmpty()
where r.prid == prid
group new {r,t,a} by new {r.testid} into g
select new PatientHistory
{
resultid = g.Select(x => x.r.resultid).Last(), // if you expect single value get it with Single()
// .... here add the rest properties
Attribute_Type = g.Select(x => x.a.Attribute_Type).Last()
}).ToList();
I appreciated this question so I thought I would add another potential usage case. I would like feedback on what the cleanest approach is to getting table information through a group operation so that I can project later in the select operation. I ended up combining what the OP did which is to pass objects into his group clause and then used the g.Select approach suggested by YD1m to get table information out later. I have a LEFT JOIN so I'm defending against nulls :
// SQL Query
//DECLARE #idCamp as Integer = 1
//
//select *,
//(select
//count(idActivityMaster)
//FROM tbActivityMasters
//WHERE dftidActivityCategory = A.idActivityCategory) as masterCount
//FROM tbactivitycategories A
//WHERE idcamp = #idCamp
//ORDER BY CategoryName
int idCamp = 1;
var desiredResult =
(from c in tbActivityCategories
.Where(w => w.idCamp == idCamp)
from m in tbActivityMasters
.Where(m => m.dftidActivityCategory == c.idActivityCategory)
.DefaultIfEmpty() // LEFT OUTER JOIN
where c.idCamp == idCamp
group new {c, m} by new { m.dftidActivityCategory } into g
select new
{
idActivityCategory = g.Select(x => x.m == null ? 0 : x.m.dftidActivityCategory).First(),
idCamp = g.Select(x => x.c.idCamp).First(),
CategoryName = g.Select(x => x.c.CategoryName).First(),
CategoryDescription = g.Select(x => x.c.CategoryDescription).First(),
masterCount = g.Count(x => x.m != null)
}).OrderBy(o=> o.idActivityCategory);
desiredResult.Dump("desiredResult");
If I just use a basic group approach I get the results but not the extra column information. At least I can't find it once I group.
var simpleGroup = (from c in tbActivityCategories
.Where(w => w.idCamp == idCamp)
.OrderBy(o => o.CategoryName)
from m in tbActivityMasters
.Where(m => m.dftidActivityCategory == c.idActivityCategory)
.DefaultIfEmpty() // LEFT OUTER JOIN
where c.idCamp == idCamp
group m by m == null ? 0 : m.dftidActivityCategory into g
select new
{
// How do I best get the extra desired column information from other tables that I had before grouping
// but still have the benefit of the grouping?
// idActivityCategory = g.Select(x => x.m == null ? 0 : x.m.dftidActivityCategory).First(),
// idCamp = g.Select(x => x.c.idCamp).First(),
// CategoryName = g.Select(x => x.c.CategoryName).First(),
// CategoryDescription = g.Select(x => x.c.CategoryDescription).First(),
// masterCount = g.Count(x => x.m != null)
idActivityCategory = g.Key,
masterCount = g.Count(x => x != null)
});
simpleGroup.Dump("simpleGroup");
Please tear this up. I'm trying to learn and it just seems like I'm missing the big picture here. Thanks.
UPDATE : Cleaned up by moving the work into the group and making the select more straight forward. If I had known this yesterday then this would have been my original answer to the OP question.
int idCamp = 1;
var desiredResult =
(from c in tbActivityCategories
.Where(w => w.idCamp == idCamp)
from m in tbActivityMasters
.Where(m => m.dftidActivityCategory == c.idActivityCategory)
.DefaultIfEmpty() // LEFT OUTER JOIN
where c.idCamp == idCamp
group new { c, m } by new
{ idActivityCategory = m == null ? 0 : m.dftidActivityCategory,
idCamp = c.idCamp,
CateGoryName = c.CategoryName,
CategoryDescription = c.CategoryDescription
} into g
select new
{
idActivityCategory = g.Key.idActivityCategory,
idCamp = g.Key.idCamp,
CategoryName = g.Key.CateGoryName,
CategoryDescription = g.Key.CategoryDescription,
masterCount = g.Count(x => x.m != null)
}).OrderBy(o => o.idActivityCategory);
desiredResult.Dump("desiredResult");
I'm trying to run the following query but for some reason MemberTransactionCount and NonMemberTransactionCount are coming back as the exact same values. It seems that the .Where() clauses aren't working as we'd expect them to.
Hoping someone can point out where I might be going wrong.
from trans in transactions
orderby trans.TransactionDate.Year , trans.TransactionDate.Month
group trans by new {trans.TransactionDate.Year, trans.TransactionDate.Month}
into grp
select new MemberTransactions
{
Month = string.Format("{0}/{1}", grp.Key.Month, grp.Key.Year),
MemberTransactionCount =
grp.Where(x => x.Account.Id != Guid.Empty || x.CardNumber != null)
.Sum(x => x.AmountSpent),
NonMemberTransactionCount =
grp.Where(x => x.Account.Id == Guid.Empty && x.CardNumber == null)
.Sum(x => x.AmountSpent)
}
EDIT
I've verified in the database that the results are not what they should be. It seems to be adding everything together and not taking into account the Account criteria that we're looking at.
I ended up solving this with two separate queries. It's not exactly as I wanted, but it does the job and seems to just as quick as I would have hoped.
var memberTrans = from trans in transactions
where trans.Account != null
|| trans.CardNumber != null
orderby trans.TransactionDate.Month
group trans by trans.TransactionDate.Month
into grp
select new
{
Month = grp.Key,
Amount = grp.Sum(x => x.AmountSpent)
};
var nonMemberTrans = (from trans in transactions
where trans.Account == null
&& trans.CardNumber == null
group trans by trans.TransactionDate.Month
into grp
select new
{
Month = grp.Key,
Amount = grp.Sum(x => x.AmountSpent)
}).ToList();
var memberTransactions = new List<MemberTransactions>();
foreach (var trans in memberTrans)
{
var non = (from nt in nonMemberTrans
where nt.Month == trans.Month
select nt).FirstOrDefault();
var date = new DateTime(2012, trans.Month, 1);
memberTransactions.Add(new MemberTransactions
{
Month = date.ToString("MMM"),
MemberTransactionCount = trans.Amount,
NonMemberTransactionCount = non != null ? non.Amount : 0.00m
});
}
I think the main problem here is that you doubt the result, though it might be correct.
Add another property for verification:
TotalAmount = grp.Sum(x => x.AmountSpent)