动态使用List <object>

时间:2017-05-14 18:52:34

标签: c# asp.net-mvc

我从2h开始搜索以填充模型中的列表。

所以我的模型如下:

 public class listePrestationtmp
    {
        public List<prestationtmp> Items { get; set; }

        [DisplayName("Sélection")]
        public List<Boolean> select { get; set; }

    } 

在我的控制器中,我要填写一个&#34; listePrestationtmp&#34;将它发送到视图,但多个项目来自我的数据库中的多个表。

所以首先我搜索我需要的id(tuteurs_id)。然后我创建一个新的listePrestationtmp,它将被发送到我的View。之后,我需要使用我的数据库给出的结果填充listePrestationtmp,具体取决于不同的tuteurs_id

int[] tuteurs_id = bdd.tuteur.Where(t => t.matricule == matricule).Select(t => t.tuteur_id).ToArray();
listePrestationtmp listPrest = new listePrestationtmp();

foreach (int i in tuteurs_id)
{
     listPrest.Items.Add(new prestationtmp());
     List<prestationtmp> tmp = bddtemp.prestationtmp.Where(p => p.tuteur_id == i).ToList();
     listPrest.Items.Add(tmp);

     /*for(int h =0; h < tmp.Items.Count(); h++)*/
     /*foreach (prestationtmp t in tmp) {
             listPrest.Items.Add(tmp);
       }*/
}

我只是无法用我需要的数据填充我的listPrestationtmp因为我无法在模型中添加项目包含。

我可能错过了愚蠢,但我从2小时开始陷入困境,我认为我的尝试越来越严重&gt;&lt;。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

试试这个:

List<prestationtmp> tmp = bddtemp.prestationtmp.Where(p => p.tuteur_id == i).ToList();
listPrest.Items.AddRange(tmp);

答案 1 :(得分:0)

否OP中的Items属性已初始化,因此在listPrest.Items.*访问

时可能会抛出空引用异常

该财产的人口可以简化为以下。

var tuteurs_ids = bdd.tuteur
    .Where(t => t.matricule == matricule)
    .Select(t => t.tuteur_id)
    .ToList();

var items = bddtemp.prestationtmp
    .Where(p => tuteurs_ids.Contains(p.tuteur_id))
    .ToList();

var listPrest = new listePrestationtmp() {
                    Items = items
                };