有彼此相关的A和B表。我想创建一个linq查询,如果B表中具有AID列的关系行的整个行等于或小于Date域中的今天的日期,则将更新A表中的Status值。
例如,根据下表,表A中ID值为1(AAA)和2(BBB)的行的Status值将为1。其状态值将不会更改,因为ID值为3的行(CCC)不小于B表中所有相关行的当前日期。
如何编写性能最稳定的linq查询?
Today : 2018-7-10 A Table ID Name Status 1 AAA 0 2 BBB 0 3 CCC 0 B Table ID AID Date 6 1 2018-5-3 7 2 2018-6-2 8 2 2018-6-4 9 3 2018-10-12 10 3 2018-7-7
答案 0 :(得分:1)
如果日期小于或等于当前日期,则将Status值设置为true。
TableB.GroupBy(x => x.AId).Select(group => new { identifier = group.Key, MaxDate = group.Max(m => m.Date) }).ToList().ForEach(y =>
{
if (y.MaxDate <= DateTime.Now.Date)
{
TableA.Where(g => g.Id == y.identifier).First().Status = true;
}
});
答案 1 :(得分:0)
然后我们更新状态值
A.Where(a => B.Where(b => b.Date <= DateTime.Now).Select(b => b.AID)。包含(a.ID))。ForEach(a => a.Status = 1)
答案 2 :(得分:0)
/*Fetching those aS Who meet the condition. */
var aList1=(from b in dbset.Bs.Where(x=>x.Date<DateTime.Now)//TimeZone may vary
join a in dbSet.As
on b.AID equals a.ID
select a);
/*Fetching those aS Who don't meet the condition. */
var aList2=(from b in dbset.Bs.Where(x=>x.Date>=DateTime.Now)//TimeZone may vary
join a in dbSet.As
on b.AID equals a.ID
select a);
/*Removing those aS from list1 which occured in list2 */
var aFinalList=(aList1.Except(aList2)).ToList();
/*Updating status */
aFinalList.ForEach(x=>x.Status=1);
aFinalList.SaveChanges();
答案 3 :(得分:0)
您可以在GroupJoin
中使用Lambda
扩展名来对Join
和A
表进行B
,然后在您的条件(日期)中使用All
扩展名<=今天或任何条件),然后更新Status
。像
var lstResult = lstA.GroupJoin(lstB, a => new { a.Id }, b => new { Id = b.AId }, (a, b) => new { a, b })
.Select(x =>
{
if (x.b.All(y => y.Date <= DateTime.Now)) //Actual condition here.
{
x.a.Status = true;
return x.a;
}
else return x.a;
});
C# fiddle和示例数据。