I've got this query
var myobjectList = from g in repository.SpeedGoalsRepository.DbSet.Where(e => e.ID == null)
from d in daysOfWeek
select new myObject
{
DayID = (short?)d,
GoalA = g.GoalA,
GoalB = g.GoalB
};
where daysOfWeek
is an enum array.
private readonly DayOfWeek[] daysOfWeek = new DayOfWeek[]
{
DayOfWeek.Sunday,
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday,
DayOfWeek.Saturday
};
so, I need to convert this query sintax to lamda expression. I try with this, but its wrong:(
var defaultSpeedGoals= repository.SpeedGoalsRepository.DbSet.Where(e => e.ID == null);
var myobjectList = SpeedGoals.Cast<SpeedGoalsRepository>()
.SelectMany(g => g.DbSet.Cast<DayOfWeek>().Select(sg => new myObject
{
DayID = (short?)sg,
GoalA= g.DbSet.FirstOrDefault().GoalA,
GoalB = g.DbSet.FirstOrDefault().GoalB
}));
The page you want to look at is here:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions
It's a lot of text. The bit you want specifically is:
A query expression with a second from clause followed by a select clause
from x1 in e1
from x2 in e2
select v
is translated into
( e1 ) . SelectMany( x1 => e2 , ( x1 , x2 ) => v )
Let's apply that to your example:
from g in repository.SpeedGoalsRepository.DbSet.Where(e => e.ID == null)
from d in daysOfWeek
select new myObject
{
DayID = (short?)d,
GoalA = g.GoalA,
GoalB = g.GoalB
};
x1
is g
e1
is repository.SpeedGoalsRepository.DbSet.Where(e => e.ID == null)
. x2
is d
e2
is daysOfWeek
v
is new myObject...
So put it all together:
repository.SpeedGoalsRepository.DbSet
.Where(e => e.ID == null)
.SelectMany(
g => daysOfWeek,
(g, d) => new myObject { ... } )
and we're done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.