1

I created a list object of class and after that m updating its value its value not updating please help me here is my code

public class LocationData
{
    public int LocId { get; set; }
    public string LocatinName { get; set; }
    public int ControlCount { get; set; }
    public Nullable<short> KeyType { get; set; }
    public Nullable<short> Financial_Reporting { get; set; }
    public Nullable<short> FraudRisk { get; set; }
    public Nullable<short> FinancialControl { get; set; }
    public Nullable<short> ELC { get; set; }
}

 var locList = location.Select(a =>
               new LocationData { LocatinName = a.Location, LocId = a.LocID });

after that I'm trying to update the value in this:

locList.Where(a => a.LocId == 7).ToList()
       .ForEach(b => b.ControlCount = b.ControlCount + 1);

but nothing is updated i also try this but not updated

(from loc in locList select loc).ToList().ForEach((loc) =>
{
   loc.ControlCount = loc.ControlCount + 1;
});
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Jatinder Sharma
  • 277
  • 1
  • 3
  • 14

2 Answers2

6

That's because you don't actually take any object materialized when lacList is declared. It's just a query definition (because LINQ execution is defered), so every time you use it new LocationDate items are created.

Call ToList() when declaring lacList and it will work:

var locList= location.Select(a => new LocationData { LocatinName = a.Location, LocId = a.LocID }).ToList();

And to be honest, I don't see why you're using List<T>.ForEach method instead od foreach loop. You have to materialize new List<T> to call that method with Where filter set on source collection. You wouldn't have to do that when using foreach:

foreach(var item in locList.Where(a => a.LocID == 7))
{
    item.ControlCount += 1;
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

You can also do like this in one line

locList.Where(o => o.LocID == 7).Select(aa => aa.ControlCount += 1).ToList();
Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58