如何使用Linq应用嵌套选择

时间:2013-11-05 00:04:13

标签: linq lambda

我正在使用嵌套选择,看起来我正在做的事情不正确!。

我正在尝试检索所有Topics项。

public class Employee
{
   public int Id{ get; set; }  
   //....other fields....
   //......
   public IList<Topics> Interest { get; set; }     
}

public class Topics
{
   public int Id { get; set; }  ;
   public string Name { get; set; }  ;
   //other fields
}

employeeItems = (from _emp in employees
                   select new Employee
                   {
                      EmpId = _emp.mediaId,
                      EmpName = _emp.mediaType,
                      ......................
                      Interest = (from _emp1 in employees.Interest  //has few rows
                      select new Topic 
                      {
                          Id = _emp1.Topics[0].Id,   //.<int>("id"), <<<ERROR
                          Name = _emp1.Topics[0].Name //["name"] <<<ERROR
                      }).ToList()

               }).ToList();
        }

1 个答案:

答案 0 :(得分:1)

Interest = (from topic in _emp.Interest.SelectMany(i=>i.Topic)  //has few rows
                      select new Topic 
                      {
                          Id = topic.Id,   //.<int>("id"), <<<ERROR
                          Name = topic.Name //["name"] <<<ERROR
                      })

public class Employee
{
   public int Id{ get; set; }  
   //....other fields....
   //......
   public IEnumberable<Topics> Interest { get; set; }     
}

将该属性保留为IEnumberable,并且不在查询中执行.ToList()。在我看来,您的数据结构是员工有多个兴趣,每个兴趣都有多个主题,这就是我使用selectmany的原因,但如果我对数据有误,你可以调整它。