[英]How to increment a number in a string?
I want to increment a number in a string. 我想增加一个字符串中的数字。
My model: 我的模特:
public partial class updown
{
public int id { get; set; }
public string number { get; set; }
}
My controller: 我的控制器:
[HttpPost]
public ActionResult Index(updown viewModel)
{
var lastPO = db.updowns
.OrderByDescending(o => o.number)
.Select(m => m.number)
.FirstOrDefault() ?? "00001";
item.number = lastPO++; // I get an error on this line
db.updowns.Add(item);
db.SaveChanges();
return View(viewModel);
}
The error: 错误:
Operator '++' cannot be applied to operand of type 'string'
运算符“ ++”不能应用于类型为“字符串”的操作数
Expected result: 预期结果:
item.number // "00002"
Based on the now-deleted comments, I have: 根据现在删除的评论,我有:
[HttpPost]
public ActionResult Index(updown viewModel)
{
var s = db.updowns
.OrderByDescending(o => o.number)
.Select(m => m.number)
.FirstOrDefault() ?? "00001/S2";
var lastPO = Convert.ToInt32(s.Substring(s.Length - 5 - 3, s.Length - 3)); // *
item.number = "EMOC-" + (++lastPO).ToString("00000");
db.updowns.Add(item);
db.SaveChanges();
return View(viewModel);
}
Expected result: 预期结果:
item.number // "EMOC-00002/S2"
But I get an error on the line marked // *
when I run it the second time. 但是第二次运行它时,在标记为
// *
的行上出现错误。
I tried doing a little bit of your code. 我尝试做一点您的代码。 It seems fine
好像还好
i think the problem lies in here 我认为问题出在这里
var s = db.updowns
.OrderByDescending(o => o.number)
.Select(m => m.number)
.FirstOrDefault() ?? "00001/S2";
the ?? "00001/S2"
?? "00001/S2"
?? "00001/S2"
might be triggering the error. ?? "00001/S2"
可能正在触发错误。 try doing a break point in var s
... and see if all of s.number has value or has a correct convertible value (there could be just letters which can't be converted) 尝试在
var s
做一个断点...并查看s.number的所有值是否都具有值或具有正确的可转换值(可能只有字母无法转换)
Expected result:
预期结果:
item.number // "EMOC-00002/S2"
You need + "/S2"
here: 您需要在此处
+ "/S2"
:
item.number = "EMOC-" + (++lastPO).ToString("00000") + "/S2";
What happens when you ran previous code the second time is that var s = "EMOC-00002"
so s.Substring(s.Length - 5 - 3, s.Length - 3)
gives "OC-00"
instead of "00002"
string, which Convert.ToInt32()
cannot handle. 第二次运行先前的代码时发生的情况是
var s = "EMOC-00002"
因此s.Substring(s.Length - 5 - 3, s.Length - 3)
给出的是"OC-00"
而不是"00002"
字符串, Convert.ToInt32()
无法处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.