更新数组,索引问题
本文关键字:问题 索引 数组 更新 | 更新日期: 2023-09-27 17:55:46
我的代码在使用mongodb c#驱动程序时遇到了问题。这个麻烦看起来像这里描述的那个: http://www.ciiycode.com/0iiBNWWexjex/how-to-update-items-in-an-arraylist-with-mongo-c-driver.html这似乎已经解决了。
我想更新文档中的二维数组。如果我使用
myarray[0,3]
它有效,但是如果我使用像这样的变量
int a = 0;
int b = 3;
myarray[a,b]
它给了我一个"无法确定表达式的序列化信息......"错误
完整代码 :
int a = 0;
int b = 3;
var update = Builders<sensorValuesDocument>.Update
.Set(e => e.values[a][b]
, new sensorValues()
{
v = 0,
t = 0,
h = 0,
c = 0,
l = 0
}) ...
和我的文档类:
public class sensorValuesDocument
{
...
public List<List<sensorValues>> values { get; set; }
...
}
public class sensorValues
{
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public float? t { get; set; }
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public float? v { get; set; }
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public float? h { get; set; }
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public float? l { get; set; }
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public float? c { get; set; }
}
如果我将前面的代码替换为.Set(e => e.values[0][3]它工作得很好。请问任何想法/解决方法?提前致谢
朱利安
我想这是MongoDB C#驱动程序的一些问题,当数组访问的索引是变量时,它无法转换整个.Set(...)
表达式树。
幸运的是,C# 是一种非常非常强大的语言,它支持表达式树,它允许您以编程方式创建表达式,如数据结构。
归根结底,你需要这样的表达式:listOfLists => listOfLists [0][3]
使用整数文字,对吧?
请参阅以下代码:
int a = 0;
int b = 3;
// This is the input parameter for the expression (i.e. the (doc) => part of the expression)
ParameterExpression valuesDocumentParameter = Expression.Parameter(typeof(sensorValuesDocument));
// This is the "values" property access. Now we would have the following expression:
// (doc) => doc.values
MemberExpression listOfListPropertyAccess = Expression.Property(valuesDocumentParameter, "values");
// This is accessing the parent list: (doc) => doc.values[0]
IndexExpression parentListIndexerAccess = Expression.Property
(
listOfListPropertyAccess,
"Item",
new Expression[] { Expression.Constant(a) }
);
// This is accessing the nested list: (doc) => doc.values[0][3]
IndexExpression nestedListIndexerAccess = Expression.Property
(
parentListIndexerAccess,
"Item",
new Expression[] { Expression.Constant(b) }
);
// This builds the full expression tree!
Expression<Func<sensorValuesDocument, sensorValues>> setExpr =
Expression.Lambda<Func<sensorValuesDocument, sensorValues>>
(
nestedListIndexerAccess,
valuesDocumentParameter
);
现在你可以给Update.Set(...)
setExpr
:Update.Set(setExpr)
。
我相信这应该可以解决MongoDB驱动程序的问题,因为您给出了它真正期望的:使用文字而不是变量进行数组访问。