C# 如何在模型绑定期间自动设置增量属性
我有一个ASP.NET核心MVC应用程序的输入请求主体,我将其绑定到C中的请求模型C# 如何在模型绑定期间自动设置增量属性,c#,asp.net-core,webhttpbinding,C#,Asp.net Core,Webhttpbinding,我有一个ASP.NET核心MVC应用程序的输入请求主体,我将其绑定到C中的请求模型 public class Request { public int Index {get;set;} public string DocType {get;set;} public string DocId {get;set;} } 这是我的请求 { "request" : [ { "DocType" : "MSWORD", "DocId"
public class Request
{
public int Index {get;set;}
public string DocType {get;set;}
public string DocId {get;set;}
}
这是我的请求
{
"request" : [
{
"DocType" : "MSWORD",
"DocId" : "553ed6c232da426681b7c45c65131d33"
},
{
"DocType" : "MSEXCEL",
"DocId" : "256ed6c232da426681b7c45c651317895"
}]
}
我想把这个请求映射到我的C模型,这样索引属性就会自动递增
换句话说,当我将我的C请求反序列化为JSON字符串时,它应该是这样的
{
"request" : [
{
"Index" : 0,
"DocType" : "MSWORD",
"DocId" : "553ed6c232da426681b7c45c65131d33"
},
{
"Index" : 1,
"DocType" : "MSEXCEL",
"DocId" : "256ed6c232da426681b7c45c651317895"
}]
}
在序列化为JSON之前,只需使用LINQ进行简单对话:
//below should be your original list instead of this test data
var list = new List<Request>
{
new Request {DocId = "000", DocType = "type"},
new Request {DocId = "111", DocType = "type"},
new Request {DocId = "222", DocType = "type"}
};
var count = 0;
var newList = list.Select(x =>
{
x.Index = count++;
return x;
}).ToList();
声明一个静态int变量来保存数字,并使用构造函数将值赋给索引
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ConsoleApp2 {
class Program {
static void Main() {
string json = @"[{'DocType' : 'MSWORD','DocId' : '553ed6c232da426681b7c45c65131d33'},{'DocType' : 'MSEXCEL','DocId' : '256ed6c232da426681b7c45c651317895'}]";
Request.Seed = 1;
var r = JsonConvert.DeserializeObject<List<Request>>(json);
Request.Seed = 100000;
r = JsonConvert.DeserializeObject<List<Request>>( json );
}
}
public class Request {
public static int Seed { get; set; }
public Request() {
Index = Seed++;
}
public int Index { get; set; }
public string DocType { get; set; }
public string DocId { get; set; }
}
}
? newList=list。选择x,index=>x。index=index….@ErikPhilips您是100%正确的。我忘了。@PiotrStapp问题中的输入是JSON字符串?如果输入是JSON反序列化到列表,然后使用上述技巧添加索引,则应用程序在整个生命周期内只能反序列化一次?您的代码仅有效一次。在第二次调用中,索引不会从零开始,而是从最后一个值开始。@PiotrStapp我不这么认为,我们应该为您编写一个完整的解决方案。@ErikPhilips谢谢您的评论,这是有效的解决方案。我希望能回答你的问题
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ConsoleApp2 {
class Program {
static void Main() {
string json = @"[{'DocType' : 'MSWORD','DocId' : '553ed6c232da426681b7c45c65131d33'},{'DocType' : 'MSEXCEL','DocId' : '256ed6c232da426681b7c45c651317895'}]";
Request.Seed = 1;
var r = JsonConvert.DeserializeObject<List<Request>>(json);
Request.Seed = 100000;
r = JsonConvert.DeserializeObject<List<Request>>( json );
}
}
public class Request {
public static int Seed { get; set; }
public Request() {
Index = Seed++;
}
public int Index { get; set; }
public string DocType { get; set; }
public string DocId { get; set; }
}
}