基于对象id加入2个对象列表

时间:2017-06-07 09:43:15

标签: c# asp.net-mvc linq

在我的Web应用程序中,我从数据库中获取了2个对象列表。

第一个对象列表员工

1 
  Name: Tom
  Week1: 1
  Week2: 3
  Week3: 7
2 
  Name: Mike
  Week1: 2
  Week2: 1
  Week3: 7

第二个对象列表 listOfId

1
  id: 1
  color: green
  symbol: AT
2
  id: 2
  color: red
  symbol: TB
3 
  id: 3
  color: blue
  symbol: TD

我希望现在能够以表格的形式显示它,对于每周,我会显示这周的颜色和符号(每周匹配Employee.Week#= listOfId.id)

像这样的东西

Name | Week1 | Week1 Color | Week1 Symbol | Week2 | Week 2 Color etc...
Tom      1       green           AT           3         blue
Mike     2       red             TB           1         green 

总的来说,每位员工将持续20周。

我考虑编写一个SQL查询,它将采用周id,并返回颜色和符号。但对于50人* 20周......我需要运行此查询1000次。

我正在寻找更好的方法来解决这个问题

我的模特:

 public class WeekViewModel
    {
        public int Id{ get; set; }
        public string ShortNAme { get; set; }
        public string Description { get; set; }
        public int Color { get; set; }
    }
}


public class EmployeeWeekViewModel
{
    public string full_name { get; set; }
    public string location { get; set; }
   public int week1 { get; set; }
    public int week2 { get; set; }
    public int week3 { get; set; }

}

1 个答案:

答案 0 :(得分:0)

如果我说得对,你有两个来自DB的列表:

  • employeesList代表员工及其相应的周数ID
  • weeksList代表员工的周数。

现在,您想要加入这两个列表,以简单表格式显示信息。我会做那样的事情:

public class EmployeeWeekViewModel{
  public string EmployeeName{get;set;}
  public WeekViewModel Week1 {get;set;}
  public WeekViewModel Week2 {get;set;}
  ...
  public WeekViewModel Week20 {get;set;}
}

public class WeekViewModel{
  public int Id{get;set;}
  public string Color{get;set;}
  public string Symbol{get;set;}
}

employeesList.Select(t=> new EmployeeWeekViewModel(){
  EmployeeName = t.Name,
  Week1 = weeksList.FirstOrDefault(w => w.id == t.Week1).Select(w => new WeekViewModel(){
    Id = w.id,
    Color = w.color,
    Symbol = w.symbol
  }),
  Week2 = weeksList.FirstOrDefault(w => w.id == t.Week2).Select(w => new WeekViewModel(){
    Id = w.id,
    Color = w.color,
    Symbol = w.symbol
  }),
  ...
});

为了不向每周提出请求,我建议您向我们查询一周的ID ID列表(checkout this example)。