0

如何将此 LINQ 查询从查询​​语法转换为方法语法?我正在执行一个共同相关的查询操作。

 var query = (from r in objEntities.Employee
              where r.Location == (from q in objEntities.Department 
                                   where q.Location == r.Location 
                                   select q.Location).FirstOrDefault()
              select new
              {
                  FirstName = r.FirstName,
                  LastName = r.LastName,
                  Age = r.Age,
                  Location = r.Location
              });
 GridView1.DataSource = query;
 GridView1.DataBind();
4

2 回答 2

1

我认为您正在尝试将查询转换为基于方法的查询而不是基于语法的查询。

var query = objEntities.Employee
                       .Where(e => e.Location == objEntities.Department
                                                            .Where(d => d.Location == r.Location)
                                                            .Select(d => d.Location)
                                                            .FirstOrDefault())
                       .Select(e => new {
                                            FirstName = e.FirstName,
                                            LastName = e.LastName,
                                            Age = e.Age,
                                            Location = e.Location
                                        });

我也很确定你在where子句中的内在表达可以用类似的东西代替:

                   .Where(e => objEntities.Department.Any(d => d.Location == e.Location)
于 2012-11-25T16:17:30.353 回答
0

Nested queries always have performance issue instead you should use join:

In the lambda expression query should be

var query = objEntities.Employee.Join(objEntities.Department, E => E.Location,
                                 D => D.Location,
                                (E,D) => new {                                          
                                                FirstName = E.FirstName,
                                                LastName = E.LastName,
                                                Age = E.Age,
                                                Location = E.Location
                                             });
于 2012-11-25T16:24:17.010 回答