Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 使用LINQ更新集合中的属性_Vb.net_Linq - Fatal编程技术网

Vb.net 使用LINQ更新集合中的属性

Vb.net 使用LINQ更新集合中的属性,vb.net,linq,Vb.net,Linq,我是Linq的新手 我的实际代码是 Dim dt As DataTable = GetData() Dim listOrder = From a In dt _ Group a By key = a("Name") Into g = Group _ Select Id = key, TotPoints = g.Sum(Function(r)r("Points")) Order B

我是Linq的新手

我的实际代码是

  Dim dt As DataTable = GetData()

  Dim listOrder = From a In dt _
                  Group a By key = a("Name") Into g = Group _
                  Select Id = key, TotPoints = g.Sum(Function(r)r("Points"))
                  Order By TotPoints Descending

  For Each item In listOrder 
      If item.Id = 1 Then
         item.TotPoints = CalculateNewPoints()
      End If
  Next
问题是,当尝试更新属性时,会收到消息:属性“xxxx”是只读的


谢谢你的帮助!!对不起,我的英语不好。

是的,应该是这样。我认为
lista
是一个打字错误,应该是
item
。这里的
item
foreach内部的迭代器是一个只读对象引用,使用它您不能像尝试的那样执行任何写入操作。而是使用
for
循环

  For Each item In listOrder 
      If item.Id = 1 Then
         item.TotPoints = CalculateNewPoints()
      End If
您也可以使用另一个LINQ查询,然后像下面这样更新数据,但只有当
Id
是唯一的并且只有Id为1的记录时,这才有效

Itemtype item = listOrder.Single(x => x.Id == 1);
item.TotPoints = CalculateNewPoints();

您正在创建匿名类型的实例
{Id,TotPoints}
。稍后,您将尝试修改
TotPoints
。但是匿名类型是不可变的,或者是只读的,所以您会得到这个异常。解决方案是立即指定正确的值:

Dim listOrder = From a In dt _
                Group a By key = a("Name") Into g = Group _
                Select _ 
                    Id = key, _
                    TotPoints = If (key = 1 _
                                    , CalculateNewPoints() _
                                    , g.Sum(Function(r)r("Points")))
                Order By TotPoints Descending

检查获取此错误的属性是否为只读或其他类型?lista的类型是什么?我猜TotPoints字段是聚合,因此无法更新。抱歉!!!!,lista.Id和lista.TotPoints是item.Id和item.TotPointsDim item=listOrder.Single(函数(r)r.Id=1)item.TotPoints=CalculateNewPoints(),相同错误“属性“TotPoints”是只读的”@Chuckg,在这种情况下,请检查类中的属性定义。看起来这是getter-only属性。我是说没有二传手在场。