C# 新手。我有一个 200 行的 .csv 文件,我将 lat/lngs 列读取为 json 格式,我想将其发布到 API,但可以发布到 API 的项目数量有限制(50 )立刻。我读到了有关 linq 批处理函数的信息,我在下面的第一个代码片段中使用了该函数,但是当我调试 foreach 语句时,helperPostBatch.Addresses 立即设置为 200 个项目,而不是 50 个。我确信我正在制作一个非常基本错误。
var helperPost = new JsonHelperPost();
var helperPostBatch = new JsonHelperPost();
List<JsonHelperPost.Response> recordsPost = new List<JsonHelperPost.Response>();
helperPost.Addresses = JsonHelperPost.ReadCoordinateCSV(wbPath).ToList();
int batchCount = 50;
foreach (var batch in helperPost.Locations.Batch(batchCount))
{
helperPostBatch.Addresses= helperPost.Addresses;
recordsPost = API.ApiIHSPostRequest(helperPostBatch);
}
public static IEnumerable<string[]> ReadCoordinateCSV(string path)
{
int index = getColumnIndex("Lat");
using (var parser = new TextFieldParser(path))
{
parser.Delimiters = new string[] { "," };
parser.ReadFields(); // read past the header
while (!parser.EndOfData)
{
yield return parser.ReadFields().Skip(index).Take(2).ToArray();
}
}
}
public List<string[]> Addresses{ get; set; }
public class Address
{
public string Lat { get; set; }
public string Long { get; set; }
}
public class Details
{
public float Test1 { get; set; }
public float Test2 { get; set; }
public float Test3 { get; set; }
public float Test4 { get; set; }
public float Test5 { get; set; }
public float Test6 { get; set; }
}
public class Response
{
public Address address;
public Details details;
}
public class API
{
public static List<JsonHelperPost.Response> ApiIHSPostRequest(JsonHelperPost helperPost)
{
using (var client = new HttpClient())
{
var result = JsonConvert.SerializeObject(helperPost);
string apiResultPost;
var endpoint = new Uri("https://api.connect");
var payload = new StringContent(result, Encoding.UTF8, "application/json");
var byteArray = Encoding.ASCII.GetBytes("Username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
apiResultPost = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
var recordsPost = JsonConvert.DeserializeObject<List<JsonHelperPost.Response>>(apiResultPost);
return recordsPost;
}
}
}
foreach (var batch in helperPost.Addresses.Batch(batchCount))
{
// Create a new instance of JsonHelperPost for this batch
var helperPostBatch = new JsonHelperPost
{
Addresses = batch.ToList() // Assign only the current batch
};
// Add the responses from this batch to the recordsPost list
recordsPost.AddRange(API.ApiIHSPostRequest(helperPostBatch));
}