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

How to set an incremental property during model binding automatically

我的 ASP.NET 核心 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 做一个简单的 "converstion":

//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; }
  }
}