linq中的两个别名求和
本文关键字:两个 别名 求和 linq | 更新日期: 2023-09-27 18:04:58
我用linq写这个查询,我想做这个工作在select new中对x和y求和2-时间跨度和多人播放,例如30
var query =
(from c in DB.SabtHoghoghs
join aa in DB.SabtHesabKarmands on c.KarmandID equals aa.KarmandID
select new
{
c.Karmand.FName,
c.BabatMah,
x = DB.SabtHesabKarmands.Where(q => q.BabatMah.Year == c.BabatMah.Year &&
q.BabatMah.Month == c.BabatMah.Month && q.HesabKarmand.HesabKarmandTypeID==1)
.Sum(aaa => aaa.Tedad * aaa.HesabKarmand.Mablagh),
y = DB.SabtHesabKarmands.Where(q => q.BabatMah.Year == c.BabatMah.Year &&
q.BabatMah.Month == c.BabatMah.Month && q.HesabKarmand.HesabKarmandTypeID == 2)
.Sum(aaa => aaa.Tedad * aaa.HesabKarmand.Mablagh),
z=y-x //how to do this(1)
karkard = (c.Karmand.ExitTime-c.Karmand.EnterTime).Hours *30 //how to do this(2)
}).Distinct();
在查询中使用let
关键字:
var query =
(from c in DB.SabtHoghoghs
join aa in DB.SabtHesabKarmands on c.KarmandID equals aa.KarmandID
let x = DB.SabtHesabKarmands.Where(q => q.BabatMah.Year == c.BabatMah.Year &&
q.BabatMah.Month == c.BabatMah.Month && q.HesabKarmand.HesabKarmandTypeID == 1)
.Sum(aaa => aaa.Tedad * aaa.HesabKarmand.Mablagh)
let y = DB.SabtHesabKarmands.Where(q => q.BabatMah.Year == c.BabatMah.Year &&
q.BabatMah.Month == c.BabatMah.Month && q.HesabKarmand.HesabKarmandTypeID == 2)
.Sum(aaa => aaa.Tedad * aaa.HesabKarmand.Mablagh)
select new
{
c.Karmand.FName,
c.BabatMah,
X = x,
Y = y,
Z = y - x, //how to do this(1)
karkard = (c.Karmand.ExitTime - c.Karmand.EnterTime).Hours * 30 //how to do this(2)
}).Distinct();
我将尽力指导你找到正确的解决方案。定义自定义类,不要使用匿名类,像这样
class MyClass
{
public string FName { get; set; }
public string BabatMah { get; set; }
public int x { get; set; }
public int y { get; set; }
public int z { get { return x - y; } }
public int karkard { get; set; }
// implement Equals and GetHashCode for correct behaviour of Distinct
}
然后选择不含z
的计算值进入MyClass
select new MyClass
{
FName = c.Karmand.FName,
BabatMah = c.BabatMah,
...
为了解决(c.Karmand.ExitTime-c.Karmand.EnterTime).Hours *30
计算,您需要带来有关ORM的更多细节。解决方案将视情况而定。一种通用的解决方案是将ExitTime
和EnterTime
提取到MyClass
中,然后以相同的方式计算小时差,就像计算x - y