C# 如何使用linq获取内存位置?
我有一个列表,我试图找到一个特定的元素,然后我想编辑该元素C# 如何使用linq获取内存位置?,c#,linq,C#,Linq,我有一个列表,我试图找到一个特定的元素,然后我想编辑该元素 storage.First(item => item.dirty == true).dirty = false; 然而,这似乎不起作用,因为我猜首先是创建另一个列表并填充它。是否有一个函数来完成我正在尝试做的事情 以下是我正在使用的数据类型: class BaseRegister { public bool dirty {set;get;} } List <BaseRegister> storage = ne
storage.First(item => item.dirty == true).dirty = false;
然而,这似乎不起作用,因为我猜首先是创建另一个列表并填充它。是否有一个函数来完成我正在尝试做的事情
以下是我正在使用的数据类型:
class BaseRegister {
public bool dirty {set;get;}
}
List <BaseRegister> storage = new List <BaseRegister> ();
类基址寄存器{
公共bool dirty{set;get;}
}
列表存储=新列表();
只有当您的类型(包含.dirty
)是类时,此选项才有效
如果这是一个结构,您将无法以这种方式改变结构。对于结构,您需要替换集合中的整个结构,使用LINQ扩展非常困难,因为它们是为查询而不是编辑而设计的
如果类型(存储的实现了IList
,例如List
,则可以使用:
int index = storage.FindIndex(item => item.dirty);
var item = storage[index];
item.dirty = false;
storage[index] = item;
请注意,这很混乱,但主要是因为它必须完全重置列表中结构的值
顺便说一句,这就是为什么可变结构是个坏主意的部分原因。如果你发现这是一种你认为你需要的模式,你可能想考虑一个类。一般来说,任何带有“dirty”标志的项都可能是可变的,因此应该是类而不是结构。如果项是引用类型,则这应该更改dirty
属性/字段
如果项是值类型,First
返回一个副本,甚至不应该编译
First不是创建列表,它返回符合条件的序列中的第一项。您的程序肯定有其他问题,让您感到困惑。为了避免疑问,这里有一个使用您的数据类型的完整程序。输出为:
---Before---
True
False
True
---After---
False
False
True
代码是:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ConsoleApplication40 {
internal class Program {
private static List<BaseRegister> storage=new List<BaseRegister>();
private static void Main(string[] args) {
storage.Add(new BaseRegister {dirty=true});
storage.Add(new BaseRegister {dirty=false});
storage.Add(new BaseRegister {dirty=true});
Dump("---Before---");
storage.First(item => item.dirty==true).dirty=false;
Dump("---After---");
}
private static void Dump(string title) {
Debug.WriteLine(title);
foreach(var br in storage) {
Debug.WriteLine(br.dirty);
}
}
private class BaseRegister {
public bool dirty { set; get; }
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统诊断;
使用System.Linq;
使用系统文本;
命名空间控制台应用程序40{
内部课程计划{
私有静态列表存储=新列表();
私有静态void Main(字符串[]args){
Add(新的基址寄存器{dirty=true});
Add(新的基址寄存器{dirty=false});
Add(新的基址寄存器{dirty=true});
转储(“---在----”);
storage.First(item=>item.dirty==true)。dirty=false;
转储(“----”之后的“-”);
}
私有静态无效转储(字符串标题){
Debug.WriteLine(标题);
foreach(存储中的var br){
Debug.WriteLine(br.dirty);
}
}
专用类基址寄存器{
公共bool dirty{set;get;}
}
}
}
是item
值还是引用类型?item是一个属性为dirty的类,但是当我尝试上面的行时,dirty仍然是true@SamFisher83第二次你是怎么检查脏的?我没有使用结构,它是一个类。类基址寄存器{bool dirty{set;get;}}我想你是对的。看起来是IDE没有正确更新监视列表中的变量,但实际上它正在更改它。