Domanda

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();
È stato utile?

Soluzione

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).

Altri suggerimenti

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

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

You can. For instance:

var data = (from a in db.Mesai select new { ... status = new List<string>() .. }).ToList();

Next, compute your status:

foreach (var item in data) {
    item.status.Add("My computed status");
} 

And then on rendering:

foreach (var item data) {
    Response.Write(item.status[0]);
}

EDIT: The list can even be intialized as per your requirement:

var data = (from a in db.Mesai select new { ... status = new List<string>(new 
string[] { c.status }) .. }).ToList();
foreach (var item in data) {
    item.status[0] = "My computed status";
} 

EDIT2: Seems like you must initialize the list, preferably with e.g. c.rowid.ToString(), otherwise the optimizer assigns the same new List() to all items, thinking that this might be some game or something.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top