Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Assign a Value to Anonymous Type's Read Only Property

I would like to create an anonymous type from linq. Then change the value of a single property(status) manually and give the list to a repeater as data source. But doesn't let me do that as theay are read-only. Any suggestion?

 var list = from c in db.Mesai
                   join s in db.MesaiTip on c.mesaiTipID equals s.ID
                   where c.iseAlimID == iseAlimID
                   select new
                   {
                       tarih = c.mesaiTarih,
                       mesaiTip = s.ad,
                       mesaiBaslangic = c.mesaiBaslangic,
                       mesaiBitis = c.mesaiBitis,
                       sure = c.sure,
                       condition = c.onaylandiMi,
                       status = c.status
                   };
 foreach (var item in list)
 {
     if (item.condition==null)
     {
          item.status == "Not Confirmed";
     }
 }
 rpCalisanMesai.DataSource = list.ToList();
 rpCalisanMesai.DataBind();
like image 351
Jude Avatar asked Jan 29 '14 11:01

Jude


2 Answers

Instead of trying to change the value after creating the list, just set the right value while creating the list.

var list = from c in db.Mesai
               join s in db.MesaiTip on c.mesaiTipID equals s.ID
               where c.iseAlimID == iseAlimID
               select new
               {
                   tarih = c.mesaiTarih,
                   mesaiTip = s.ad,
                   mesaiBaslangic = c.mesaiBaslangic,
                   mesaiBitis = c.mesaiBitis,
                   sure = c.sure,
                   condition = c.onaylandiMi,
                   status = c.onaylandiMi != null ? c.status : "Not Confirmed"
               };

Also, if you could change the property, your problem would be executing the query twice: first in the foreach-loop, and then again by calling list.ToList() (which would create new instances of the anonymous type).

like image 173
sloth Avatar answered Nov 14 '22 23:11

sloth


You cannot, anonymous type's properties are read-only.

You need to set it during object creation. See @Dominic answer for code sample.

like image 37
Jakub Konecki Avatar answered Nov 14 '22 21:11

Jakub Konecki