简体   繁体   中英

Looping through IEnumerable using ForEach in C#

I'm trying to loop through an IEnumerable but for some reason it is not going through the foreach loop, as the values for each ChartClass was not modified.

public IEnumerable<ChartClass> get(string ID, string buildname, string placeholder)
    {
        var context = new Entities();
        var metrics = from c in context.VSTS_CODE_METRICS
                      where c.BUILD_NAME == buildname && c.OBJECT_TYPE == "Namespace"
                      group c by c.BUILD_ID into g
                      select new ChartClass
                      {
                          Build_ID = g.Key,
                          BuildTrim = g.Key,
                          Index = g.Average(c => c.MAINTAINABILITYINDEX_).Value
                      };
        foreach (var i in metrics)
        {
            int num = i.BuildTrim.LastIndexOf('_');
            i.BuildTrim = "2";
        }       
        return metrics;
    }

I'm trying to change each ChartClass' BuildTrim field to "2" but it's not happening for some reason

Why don't you just set the BuildTrim equal to "2" in the query?

public IEnumerable<ChartClass> get(string ID, string buildname, string placeholder)
    {
        var context = new Entities();
        var metrics = from c in context.VSTS_CODE_METRICS
                      where c.BUILD_NAME == buildname && c.OBJECT_TYPE == "Namespace"
                      group c by c.BUILD_ID into g
                      select new ChartClass
                      {
                          Build_ID = g.Key,
                          BuildTrim = "2",//g.Key,
                          Index = g.Average(c => c.MAINTAINABILITYINDEX_).Value
                      };
        /*foreach (var i in metrics)
        {
            int num = i.BuildTrim.LastIndexOf('_');
            i.BuildTrim = "2";
        }*/       
        return metrics;
    }

metrics is an IQueryable . Every single time you iterate the object it is going to to to the database, query the items that you're asking for, put them into the objects that you specified, and then allow those objects to be iterated. You're modifying the objects that are being returned, but those same in-memory objects won't be used if you iterate the sequence again. Instead it's going back to the database a second time and pulling back a fresh query that doesn't have your changes.

As mentioned in the other answer, if you simply modify your first Select call to set BuildTrim to the desired value to begin with, rather than modifying an object that is just about to be thrown away, your query will work as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM