如何更新集合类型对象中的值

时间:2013-12-27 05:22:50

标签: c#

我创建了一个类的列表对象,之后更新了它的值,它的值没有更新请帮我这里是我的代码

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 });

之后,我正在尝试更新此值:

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

但没有更新任何我也尝试这个但没有更新

(from loc in locList select loc).ToList().ForEach((loc) =>
{
   loc.ControlCount = loc.ControlCount + 1;
});

2 个答案:

答案 0 :(得分:6)

那是因为在声明lacList时你实际上没有实现任何物体。它只是一个查询定义(因为延迟了LINQ执行),因此每次使用它时都会创建新的LocationDate项。

在声明ToList()时致电lacList,它会起作用:

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

说实话,我不明白为什么你使用List<T>.ForEach方法而不是od foreach循环。您必须具体化新List<T>以使用源集合上设置的Where过滤器调用该方法。使用foreach

时,您不必这样做
foreach(var item in locList.Where(a => a.LocID == 7))
{
    item.ControlCount += 1;
}

答案 1 :(得分:1)

您也可以在一行中执行此操作

locList.Where(o => o.LocID == 7).Select(aa => aa.ControlCount += 1).ToList();