Pergunta

I have multiple select statements that fetch result as list and I need to add this list finally to bind to a dropdown.Currently this is what I am doing..

 public void load()
{
    try
    {

        using (DataContext db = new DataContext())
        {
            var cm = (from c in db.COMPANY_MASTERs
                      select c).FirstOrDefault();

            if (Convert.ToBoolean(cm.PLANT))
            {
                var Div = (from vp in db.PLANT
                           select new
                           {
                               ID = vp.PLANT_ID,
                               NAME = vp.PLANT_NAME
                           }).ToList();
            }
            if (Convert.ToBoolean(cm.ANIMAL))
            {
                var Dep = (from vp in db.ANIMAL
                           select new
                           {
                               ID = vp.ANIMAL_ID,
                               NAME = vp.ANIMAL_NAME
                           }).ToList();
            }
            //this is what I am trying to do but cant,since the variables are nested                inside if.

              Div.AddRange(Dep);
            ddl.DataTextField = "NAME";
            ddl.DataValueField = "ID";
            ddl.DataSource = Div;
            ddl.DataBind();
}

This is my question,

1.How can I overcome this anonymous type error and bind the added list to dropdown.

Thanks

Foi útil?

Solução

When you select, create a new instance of your Variable type, not an anonymous select :

var Div = (from vp in db.PLANT
           select new Variable()
           {
               ID = vp.PLANT_ID,
               GENDER = vp.PLANT_NAME
           }).ToList();

Then do the same with your Dep variable :

var Dep = (from vp in db.ANIMAL
           select new
           {
               ID = vp.ANIMAL_ID,
               GENDER = vp.ANIMAL_NAME
           }).ToList();

And you'll be able to AddRange()


Edit : Your variable need to be in the same scope to be used together.. You should declare them (strongly typed) up top of your function. (thanks andrii.litvinov)

List<Variable> Div;
List<Variable> Dep;

Outras dicas

You can initialize lstVar and add the contents of the other two lists using successive foreach loops

In addition to Gabriel GM answer you should declare variables before first if.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top