Interpreting Sql with where and having statement to linq giving different results - c#

Please - I have this SQL statement:
SELECT FK_ClassId, LectureDays
FROM tbl_TimeTables
WHERE Term = 'First Term'
AND FK_session = 4
AND fk_classId = 1
AND (fk_subjectid <> 1)
GROUP BY FK_classId, LectureDays
HAVING (COUNT(*) < 6)
This returns this result:
Image Embedded Here, giving the right result
But when I interpret to linq, I get the a different result:
Tbl_TimeTables.GroupBy(x => new { x.FK_Session, x.Term, x.LectureDays,
x.FK_ClassId, x.FK_SubjectId })
.Where(grp => grp.Count() < 6 && grp.Key.FK_Session == 4 && grp.Key.Term ==
"First Term" && grp.Key.FK_ClassId == 1 && grp.Key.FK_SubjectId != 1)
.Select(grp => new
{
LectureDay = grp.Key.LectureDays,
ClassId = grp.Key.FK_ClassId
})
Wrong Results Picture Link here
Please look at my code, what am I doing wrong?
Thanks
Tim

This is the right way the linq query should go according to Matt Gibson's suggestion:
Tbl_TimeTables
.Where(x => x.FK_Session == 4 && x.Term == "First Term" && x.FK_ClassId == 1
&& x.FK_SubjectId != 1)
.GroupBy(x => new { x.FK_ClassId, x.LectureDays })
.Where(grp => grp.Count() < 6)
.Select(grp => new
{
ClassId = grp.Key.FK_ClassId,
LectureDay = grp.Key.LectureDays
})
This works exactly like the sql
Also to point out that this link: http://www.dotnettricks.com/learn/sqlserver/definition-use-of-group-by-and-having-clause helped me in understanding how the having statement works, which helped in seeing what Matt what saying.

Related

where clause not working in group by LINQ c sharp

I have a table "register_operation with fields"
[Key]
int id_registru_casa ,
DateTime data ,
int id_cont_sintetic ,
decimal suma ,
string tip
tip can take only 2 value :"receipts" and "payments"
"Groupby" work with no problem
but when I add "where" clause not working
(it doesn't show me any records)
(although there are recordings in database with day 19, month 9 and tip=receipts)
var centralizator_rc = db.register_operation
.Where(i => (i.data.Day == 19) && (i.data.Month == 9) && (tip=="receipts"))
.GroupBy(i => i.id_cont_sintetic)
.Select(g => new {
id_cont_sintetic = g.Key,
total_receipts = g.Sum(i=>i.suma),
}).ToList();
Thanks!
SOLVED!
I change code like this:
var centralizator_rc = db.registru_casa
.Where(crc=>(crc.data.Month==8) && (crc.data.Day==16) && (crc.tip=="receipts"))
.GroupBy(crc=> new
{
crc.id_cont_sintetic,
crc.data.Month,
crc.data.Day,
crc.tip
})
.Select(g => new {
data = ziuaOK,
id_cont_sintetic = g.Key.id_cont_sintetic,
total_incasare = g.Sum(i => i.suma),
}).ToList();

Difference between LINQ Lambda and SQL statement

I have the following lambda statement:
var resources = Db.Resource.Where(w => w.ResValue.Any(a => a.ApplicationFk == applicationPk) && w.CategoryFk == (categoryId ?? w.CategoryFk ) && w.IsEditable);
if (cultureIdsMissing!= null)
{
resources = resources.Where(w => w.ResValue.Any(a => cultureIdsMissing.Any(aa => aa == a.CultureFk) && a.Value == string.Empty));
}
This is not returning the result which I want, which is returned by:
SELECT Resource.ResourcePk, Resource.CategoryFk, Resource.Name, Resource.IsEditable, ResValue.ApplicatieFk, ResValue.CultureFk, ResValue.Value
FROM Resource
INNER JOIN ResValue ON Resource.ResourcePk = ResValue.ResourceFk
WHERE (ResValue.ApplicatieFk = 6)
AND (Resource.IsEditable = 1)
AND (ResValue.Value = '')
AND (ResValue.CultureFk = 1 OR ResValue.CultureFk = 2)
Not that cultureIdsMissing is a List containing both the numbers 1 and 2.
What am I missing or doing wrong with the lambda query?
I think you have to remove && w.CategoryFk == (categoryId ?? w.CategoryFk ) from your linq lemda expression. if categoryId = 1 then it will take only records with value 1. So try after remove that. Your linq code should be this.
var resources = Db.Resource.Where(w => w.ResValue.Any(a => a.ApplicationFk == applicationPk)&& w.IsEditable);
if (cultureIdsMissing!= null)
{
resources = resources.Where(w => w.ResValue.Any(a => cultureIdsMissing.Any(aa => aa == a.CultureFk) && a.Value == string.Empty));
}
You should take it from your sql statement :
Db.Resource
.Join(Db.ResValue
, rs => rs.ResourcePk
, resV => resv.resourceFk
, (rs, resv) => new { res = rs, resV = resV })
.Where(w => w.resv.ApplicatieFk == 6
&& w.res ==1
&& resv.Value == string.empty()
&& (resv.CultureFk == 1 || resv.CultureFk == 2))
It's not tested so maybe it won't work on first try.
I would translate the SQL to query comprehension syntax. In general, convert phrases in query comprehension order, use table aliases as range variables (or create range variables), and put unary/overall aggregate functions (such as TOP, DISTINCT or SUM) as function calls outside the whole query. For your SQL,
var ans = from r in Resource
where r.IsEditable == 1
join rv in ResValue on r.ResourcePk equals rv.ResourceFk
where rv.ApplicatieFk == 6 && rv.Value == "" && (rv.CultureFk == 1 || rv.CultureFk == 2)
select new { r.ResourcePk, r.CategoryFk, r.Name, r.IsEditable, rv.ApplicatieFk, rv.CultureFk, rv.Value };

Improve performance in linq query - trying to change the query from subquery to join

I am doing the below linq query which is costing me a lot and this query is in a loop which I can not avoid and I have to do it in C# which also I can not avoid. I have lot of logic above the linq query and after the query. I wanted to check if I can change anything on the query to improve the performance at least a little bit.
lstDataTable.Where(i => i.Field<int>("ALLL_Snapshot_ID") == 20 &&
i.Field<int>("ALLL_Analysis_Segment_Group_Column_ID") == 5 &&
i.Field<DateTime>("OriginationDate") > startingSnapshotDate &&
i.Field<DateTime>("OriginationDate") <= endingSnapshotDate &&
snapshotDataWithDate.Select(j => j.Field<string>
("MaturityDateBorrowerIdNoteNumberKey")).Contains(i.Field<string>
("MaturityDateBorrowerIdNoteNumberKey")) &&
snapshotDataWithDate.Select(j => j.Field<string>
("OriginationDateBorrowerIdNoteNumberKey")).Contains(i.Field<string>
("OriginationDateBorrowerIdNoteNumberKey")))
.Select(i => i.Field<Decimal>("BalanceOutstanding") + i.Field<Decimal>
("UndisbursedCommitmentAvailability")).Sum();
where lstDataTable and snapshotDataWithDate are IEnumerable of DataRow.
I tried above query using join but it is not joining properly. The difference between the two results is way high. Below is the query I tried using join
(from p in lstDataTable
join t in snapshotDataWithDate on p.Field<string>
("MaturityDateBorrowerIdNoteNumberKey") equals t.Field<string>
("MaturityDateBorrowerIdNoteNumberKey") &&
p.Field<string>("OriginationDateBorrowerIdNoteNumberKey") equals
t.Field<string>("OriginationDateBorrowerIdNoteNumberKey")
where p.Field<int>("ALLL_Analysis_Segment_Group_Column_ID") ==
SegmentGroupCECLSurvivalRateObj.ALLL_Segment_Group_Column_ID &&
p.Field<DateTime>("OriginationDate") > startingSnapshotDate &&
p.Field<DateTime>("OriginationDate") <= endingSnapshotDate
select p.Field<Decimal>("BalanceOutstanding") + p.Field<Decimal>
("UndisbursedCommitmentAvailability")).Sum();
Try this query, I have changed some expressions in where clause.
lstDataTable.Where(i => i.Field<int>("ALLL_Snapshot_ID") == 20 &&
i.Field<int>("ALLL_Analysis_Segment_Group_Column_ID") == 5 &&
i.Field<DateTime>("OriginationDate") > startingSnapshotDate &&
i.Field<DateTime>("OriginationDate") <= endingSnapshotDate &&
snapshotDataWithDate.Any(j => j.Field<string>
("MaturityDateBorrowerIdNoteNumberKey") == i.Field<string>
("MaturityDateBorrowerIdNoteNumberKey")) &&
snapshotDataWithDate.Any(j => j.Field<string>
("OriginationDateBorrowerIdNoteNumberKey") == i.Field<string>
("OriginationDateBorrowerIdNoteNumberKey")))
.Select(i => i.Field<Decimal>("BalanceOutstanding") + i.Field<Decimal>
("UndisbursedCommitmentAvailability")).Sum();
Perhaps pulling out the Field accesses will provide a small amount of optimization?
var snapshotDataConvertedMDB = snapshotDataWithDate.Select(r => r.Field<string>("MaturityDateBorrowerIdNoteNumberKey")).ToList();
var snapshotDataConvertedODB = snapshotDataWithDate.Select(r => r.Field<string>("OriginationDateBorrowerIdNoteNumberKey")).ToList();
var ans = lstDataTable
.Select(r => new {
ALLL_Snapshot_ID = r.Field<int>("ALLL_Snapshot_ID"),
ALLL_Analysis_Segment_Group_Column_ID = r.Field<int>("ALLL_Analysis_Segment_Group_Column_ID"),
OriginationDate = r.Field<DateTime>("OriginationDate"),
MaturityDateBorrowerIdNoteNumberKey = r.Field<string>("MaturityDateBorrowerIdNoteNumberKey"),
OriginationDateBorrowerIdNoteNumberKey = r.Field<string>("OriginationDateBorrowerIdNoteNumberKey"),
BalanceOutstanding = r.Field<Decimal>("BalanceOutstanding"),
UndisbursedCommitmentAvailability = r.Field<Decimal>("UndisbursedCommitmentAvailability")
})
.Where(i => i.ALLL_Snapshot_ID == 20 &&
i.ALLL_Analysis_Segment_Group_Column_ID == 5 &&
i.OriginationDate > startingSnapshotDate &&
i.OriginationDate <= endingSnapshotDate &&
snapshotDataConvertedMDB.Contains(i.MaturityDateBorrowerIdNoteNumberKey) &&
snapshotDataConvertedODB.Contains(i.OriginationDateBorrowerIdNoteNumberKey))
.Select(i => i.BalanceOutstanding + i.UndisbursedCommitmentAvailability)
.Sum();

Query nested linked lists

I'm trying to query a nested linked list where result is the product of a child value multiplied by values in the parent list, and then the result is added.
This code works:
var X = (from B in Main.Globals.BookLL
from G in B.GreeksLL
where B.DealNo == 1 && B.Strategy == "Condor" &&
G.BookOrComp == "Book" && G.GreekType == "Delta"
select new
{
Total = G.Data[3] * B.BookPosn * B.FxRate
}).Sum(s=>s.Total);
...but I'd prefer to use lambda. This code below gives the compile error shown as a comment at the end of the line.
double Z = Globals.BookLL.Where(B => B.DealNo == 1 && B.Strategy == "Condor").
SelectMany(G => G.GreeksLL).
Where(G => G.BookOrComp == "Book" && G.GreekType == "Delta").
Select(G => new { Total = G.Data[3] * B.BookPosn*B.FxRate }). // Compile error "B does not exist in the current context"
Sum();
I don't know how to do this, please take a look and correct the query? Thanks.
Try:
double Z = Globals.BookLL.Where(B => B.DealNo == 1 && B.Strategy == "Condor").
SelectMany(par => par.GreeksLL, (parent, child) => new { G = child, B = parent }).
Where(both => both.G.BookOrComp == "Book" && both.G.GreekType == "Delta").
Select(both => new { Total = both.G.Data[3] * both.B.BookPosn*both.B.FxRate }).
Sum(x => x.Total);
My naming is a bit weird, but I hope you get the idea, basically you 'abandoned' B when you did SelectMany(), and this should be the way.
It is untested, so let me know if it works.
See MSDN for SelectMany() with results selector function.
Another approach is to filter the GreekLL inside the SelectMany using this overload, and then use Sum extension:
double z = Main.Globals.BookLL.Where(book => book.DealNo == 1 && book.Strategy == "Condor")
.SelectMany(book => book.GreeksLL.Where(greek => greek.BookOrComp == "Book" && greek.GreekType == "Delta")
,(book, greek) => new { Greek = greek, Book = book })
.Sum(greekAndBook => greekAndBook.Book.BookPosn * greekAndBook.Book.Fxrate * greekAndBook.Greek.Data[3]);

c# - Group by and having with two counts in Linq

How can I write the follow query with Linq in C#?
SELECT MAX(A2.LINHA_PLANILHA)
FROM MD_IMP_FORCA_VENDA_DADOS_A2 A2
WHERE A2.LINHA <> '0'
AND TRIM(A2.SETORES) IS NOT NULL
AND A2.LINHA_PLANILHA <> 1
AND USUARIO = V_USUARIO
GROUP BY A2.LINHA, A2.BRICK
HAVING COUNT(A2.BRICK) > 1 AND COUNT(DISTINCT A2.SETORES) > 1;
I thought to do this:
var result = from r in dataTable.AsEnumerable()
where r.Field<string>(1) != "0"
&& r.Field<string>(2).Trim() != null
&& r.Field<Int32>(0) != 1
group r by new {Linha = r.Field<string>(1), Brick = r.Field<string>(3) } into temp
where temp.Count() > 1
select new { MaxLinha = (from r2 in temp select r2.Field<Int32>(0)).Max()};
But I don't know how to put the two COUNTS of HAVING clause in Linq query.
Any help would be appreciated.
Thanks
Zago
Perhaps:
var query = db.MD_IMP_FORCA_VENDA_DADOS_A2
.Where(x => x.LINHA != "0"
&& x.SETORES != null
&& x.SETORES.Trim() != ""
&& x.LINHA_PLANILHA <> 1
&& x.USUARIO = x.V_USUARIO
)
.GroupBy(x => new { x.LINHA, x.BRICK })
.Where(g => g.Count() > 1 && g.Select(x => x.SETORES).Distinct().Count() > 1)
.Select(g => g.Max(x => x.LINHA_PLANILHA));

Categories