根据linq查询的结果更新属性

时间:2010-11-18 09:14:02

标签: c# linq

我正在尝试使用linq对某些数据进行分组,然后根据查询中的值更新某个数据。

e.g。

 var list = from c in Transactions()
                group c by c.StoreID into g
                select new TransactionDetail{ 
                  Description = g.FirstOrDefault().Descrip,
                  BusinessName = g.FirstOrDefault().BusinessName,
                  TransactionAmount = g.Where(cr => cr.EntryType == cnCommon.INSERT_ENTRY).Sum(cr=>cr.TransactionAmount).Value,
                 PurchasesRequired = g.FirstOrDefault().PurchasesNeeded

                };

        foreach (TransactionDetail item in list)
        {
            item.ProgressBar = (230 / item.PurchasesRequired) *Convert.ToInt32(item.TransactionAmount);
        }


        lstTransactions.DataSource = list.ToList();
        lstTransactions.DataBind();


    }

    public class TransactionDetail
    {
        public string Description { get; set; }
        public string BusinessName { get; set; }
        public double TransactionAmount { get; set; }
        public double TransactionsCompleted { get; set; }
        public int PurchasesRequired { get; set; }
        public bool IsRedeemable { get; set; }
        public int Balance { get; set; }
        public int ProgressBar { get; set; }
    }

查询工作正常,但是当我执行foreach循环时,TransactionDetail.ProgressBar没有更新。

你能看出我做错了吗?

2 个答案:

答案 0 :(得分:0)

这里可能存在的一个问题是等式的以下部分

(230 / item.PurchasesRequired)

item.PurchasesRequired是一个int,因此如果它高于230,则结果为0,当你将0乘以item.TransactionAmount时,无论TransactionAmoutn值如何,它仍为0。即使PurchasesRequired低于230,它也会非常不经常,因为购买需求230和120会给你相同的结果。

尝试形成这样的公式:

(int)((230*item.TransactionAmount) / item.PurchasesRequired)

答案 1 :(得分:0)

什么是交易()?这是LINQ-to-Objects还是LINQ-to-SQL?

也许你不能在循环中修改列表中对象的属性。尝试将“.ToList()”添加到“list”中,如下所示:

var list = (from c in Transactions() 
           group c by c.StoreID into g 
           select new TransactionDetail{  
               Description = g.FirstOrDefault().Descrip, 
               BusinessName = g.FirstOrDefault().BusinessName, 
               TransactionAmount = g.Where(cr => cr.EntryType == cnCommon.INSERT_ENTRY).Sum(cr=>cr.TransactionAmount).Value, 
               PurchasesRequired = g.FirstOrDefault().PurchasesNeeded  
                }).ToList(); 

然后循环结果。