如何在模型绑定期间自动设置增量属性



我有一个 ASP.NET Core MVC应用程序的输入请求正文,我正在将其绑定到C#中的请求模型。

public class Request 
{
    public int Index {get;set;}
    public string DocType {get;set;}
    public string DocId {get;set;}
}

这是我的请求 JSON

{
"request" : [
    {
        "DocType" : "MSWORD",
        "DocId"   : "553ed6c232da426681b7c45c65131d33"
    },
    {
        "DocType" : "MSEXCEL",
        "DocId"   : "256ed6c232da426681b7c45c651317895"
    }]
}

我想将此请求映射到我的 C# 模型,以便 Index 属性自动递增。

换句话说,当我将 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();

更新感谢Erik和他在上面的评论,代码可以简化为

var newList = list.Select((x, index) =>
{
    x.Index = index;
    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; }
  }
}

相关内容

  • 没有找到相关文章

最新更新