我们有一些用户数据,在某个时候,我们希望为满足某些条件的用户修改用户数据值。例如:当用户在线时间超过100小时时,我们可以添加额外的10个金币。
现在我使用下面的代码对数据进行调整
<!-- language: c# -->
public void UserBounds(List<userdata> DataList)
{
DataList.Where(p => p.Onlinetime > 100).Select(x =>
{
x.Bound = x.Bound + 10;
return x;
}).ToList();
DataList.Where(p => p.isFirstLogin).Select(x =>
{
x.Bound = x.Bound + 1;
return x;
}).ToList();
}现在条件要高得多,我想使用字符串表达式来执行这些操作,我在List.like sql和update语法上设置了过滤器和奖励。
例如
?
过滤界>100界=界+ 10-------------------------------------------isFirstLogin界=界+5?
现在我使用system.linq.dynamic,它可以使用筛选字符串作为where表达式,但是如何从边界字符串生成表达式语句。喜欢
“绑定=绑定+ 10",表达式为
x =>{
x.Bound = x.Bound + 10;
return x;
};谢谢各位。
发布于 2018-10-07 15:51:36
提醒您,Linq用于查询数据,而不是更新数据。查询可以将数据转换为另一种形式。
void Main()
{
var data = new []
{
new Data { IsFirstLogin = true , OnlineTime = 0, Bound = 0 }, // bound + 5
new Data { IsFirstLogin = true , OnlineTime = 101, Bound = 0 }, // bound + 15
new Data { IsFirstLogin = false, OnlineTime = 50, Bound = 10 }, // bound + 0
new Data { IsFirstLogin = false, OnlineTime = 200, Bound = 25 }, // bound + 10
};
var query = data
.Select(x =>
{
x.Bound +=
x.IsFirstLogin && x.OnlineTime > 100 ? 15 :
x.IsFirstLogin ? 5 :
x.OnlineTime > 100 ? 10 : 0;
return x;
}
)
.Dump() // remove this line if not in LinqPad
;
}
public class Data
{
public bool IsFirstLogin { get; set; }
public int OnlineTime { get; set; }
public int Bound { get; set; }
}LinqPad的结果:

替代解决方案,将2个未映射属性添加到类中。
void Main()
{
var data = new []
{
new Data { IsFirstLogin = true , OnlineTime = 0, Bound = 0 }, // bound + 5
new Data { IsFirstLogin = true , OnlineTime = 101, Bound = 0 }, // bound + 15
new Data { IsFirstLogin = false, OnlineTime = 50, Bound = 10 }, // bound + 0
new Data { IsFirstLogin = false, OnlineTime = 200, Bound = 25 }, // bound + 10
};
var query = data
.Select(x =>
{
x.Bound += x.GetBoundIsFirstLogin + x.GetBoundOnlineTime;
return x;
}
)
.Dump() // remove this line if not in LinqPad
;
}
public class Data
{
public bool IsFirstLogin { get; set; }
public int OnlineTime { get; set; }
public int Bound { get; set; }
[NotMapped]
public int GetBoundIsFirstLogin => IsFirstLogin ? 5 : 0;
[NotMapped]
public int GetBoundOnlineTime => OnlineTime > 100 ? 10 : 0;
}发布于 2018-10-07 19:17:06
谢谢韩。
1.Linq可以更新列表的项值,如下所示
var datas = data.ToList();
datas.Select(p => {
p.Bound=p.Bound+100;
return p;
}).ToList();
datas.Dump();2.键不是更新列表数据,在我的数据中,需要根据多个条件更改数据的结果,因此代码定义的条件不适用,只能动态生成相应的表达式,然后使用该表达式更新数据,键将字符串转换为lambda表达式。例如将"Bound=Bound+10"转换为表达式
x=>{x.Bound = x.Bound + 10;
return x;}3.我认为可能使用Expression<Action<data>> or Expression<Action<data,data>>,但我还没有找到测试它的方法。
https://stackoverflow.com/questions/52690136
复制相似问题