¿Actualizar una propiedad de elemento dentro de IEnumerable pero la propiedad no permanece configurada?

I have two tables: Transactions and TransactionAgents. TransactionAgents has a foreign key to Transactions called TransactionID. Pretty standard.

También tengo este código:

BrokerManagerDataContext db = new BrokerManagerDataContext();

var transactions = from t in db.Transactions
                   where t.SellingPrice != 0 
                   select t;

var taAgents = from ta in db.TransactionAgents
               select ta;

foreach (var transaction in transactions)
{
    foreach(var agent in taAgents)
    {
        agent.AgentCommission = ((transaction.CommissionPercent / 100) * (agent.CommissionPercent / 100) * transaction.SellingPrice) - agent.BrokerageSplit;
    } 
}

dataGridView1.DataSource = taAgents;

Basically, a TransactionAgent has a property/column named AgentCommission, which is null for all TransactionAgents in my database.

My goal is to perform the math you see in the foreach(var agent in taAgents) to patch up the value for each agent so that it isn't null.

Oddly, when I run this code and break-point on agent.AgentCommission = (formula) it shows the value is being calculated for AgentCommissision and the object is being updated but after it displays in my datagrid (used only for testing), it does not show the value it calculated.

So, to me, it seems that the Property isn't being permanently set on the object. What's more, If I persist this newly updated object back to the database with an update, I doubt the calculated AgentCommission will be set there.

Without having my table set up the same way, is there anyone that can look at the code and see why I am not retaining the property's value?

preguntado el 01 de febrero de 12 a las 22:02

5 Respuestas

IEnumerable<T>s do not garantizar that updated values will persist across enumerations. For instance, a List will return the same set of objects on every iteration, so if you update a property, it will be saved across iterations. However, many other implementations of IEnumerables return a new set of objects each time, so any changes made will not persist.

If you need to store and update the results, pull the IEnumerable<T> hasta un List<T> usar .ToList() or project it into a new IEnumerable<T> usar .Select() with the changes applied.

To specifically apply that to your code, it would look like this:

var transactions = (from t in db.Transactions
                    where t.SellingPrice != 0 
                    select t).ToList();

var taAgents = (from ta in db.TransactionAgents
                select ta).ToList();

foreach (var transaction in transactions)
{
    foreach(var agent in taAgents)
    {
        agent.AgentCommission = ((transaction.CommissionPercent / 100) * (agent.CommissionPercent / 100) * transaction.SellingPrice) - agent.BrokerageSplit;
    } 
}

dataGridView1.DataSource = taAgents;

respondido 05 nov., 19:03

Oh. Thats nice to know. So, I need to .ToList() my enumerable before I foreach over them? - Isaías Nelson

Yes, that way the values will be stored locally in the List instead of temporarily in a disposed-of object. - eouw0o83hf

-1 This answer is simply Mal. You definitely can change object properties that are accessed via IEnumerable. El List sí mismo implementa IEnumerable.... ken2k

On another look, you're right - I guess the more correct description is an IEnumerable no garantizar that updating its values will persists across enumerations. - eouw0o83hf

I did go crazy with this :) Thanks so much. - QMaster

Specifically, the problem is that each time you access the IEnumerable, it enumerates over the collection. In this case, the collection is a call to the database. In the first part, you're getting the values from the database and updating them. In the second part, you're getting the values from the database again and setting that as the datasource (or, pedantically, you're setting the enumerator as the datasource, and then that is getting the values from the database).

Use .ToList() or similar to keep the results in memory, and access the same collection every time.

Respondido 02 Feb 12, 02:02

Wow. So the problem is much worse than eow0o83hf described. I understand that its sort of "readonly" but the enumerable is essentially wiping out the values as the collection is read. - Isaías Nelson

It's not so much that it's wiping out the values, but that it's reading from a different collection. (In simple (but not technically correct) terms, it creates a new "collection" every time you enumerate it) - Kyle W

Assuming you are using LINQ to SQL, if EnableObjectTracking is false, then the objects will be constructed new every time the query is run. Otherwise, you would be getting the same object instances each time and your changes would survive. However, like others have shown, instead of having the query execute multiple times, cache the results in a list. Not only will you get what you want working, you'll have fewer database round trips.

Respondido 02 Feb 12, 04:02

I found that I had to locate the item in the list that I wanted to modify, extract the copy, modify the copy (by incrementing its count property), remove the original from the list and add the modified copy. var x = stats.Where(d => d.word == s).FirstOrDefault(); var statCount = stats.IndexOf(x); x.count++; stats.RemoveAt(statCount); stats.Add(x);

respondido 28 nov., 16:22

This is very inefficient and bad coding practice. You really should not use LINQ for this, especially with lists. just use the normal operator[]. - JHBonarius

It is helpful to rewrite your LINQ expression using lambdas so that we can consider the code in more explicit terms.

//Original code from question
var taAgents = from ta in db.TransactionAgents
               select ta;
//Rewritten to explicitly call attention to what Select() is actually doing
var taAgents = db.TransactionAgents.Select(ta => new TransactionAgents(/*database row's data*/)});

In the rewritten code, we can clearly see that Select() is construcción a nuevo objeto based on each row returned from the database. What's more, this object construction occurs cada vez los IEnumerable taAgents is iterated through.

So, explained more concretely, if there are 5 TransactionAgents rows in the database, in the following example, the TransactionAgents() constructor is called a total of 10 times.

// Assume there are 5 rows in the TransactionAgents table
var taAgents = from ta in db.TransactionAgents
               select ta;

//foreach will iterate through the IEnumerable, thus calling the TransactionAgents() constructor 5 times
foreach(var ta in taAgents)
{
  Console.WriteLine($"first iteration through taAgents - element {ta}");
}
// these first 5 TransactionAgents objects are now out of scope and are destroyed by the GC


//foreach will iterate through the IEnumerable, thus calling the TransactionAgents() constructor 5 MORE times
foreach(var ta in taAgents)
{
  Console.WriteLine($"second iteration through taAgents - element {ta}");
}

// these second 5 TransactionAgents objects are now out of scope and are destroyed by the GC

As we can see, all 10 of our TransactionAgents objects were creado mediante el lambda en nuestro Select() method, and do no exist outside of the scope of the foreach .

Respondido el 21 de junio de 21 a las 20:06

Not exactly. The method-syntax equivalent is db.TransactionAgents.Select(ta=> ta). - Gert Arnold

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.