我的WebAPI收到两个字符串,一个包含显示值(名称),一个包含隐藏值(电子邮件)。
之前,它只收到一个字符串,使用了foreach,我不确定如何让它与两个一起工作,如何填写“nameslist”中的“name”:< / p>
[System.Web.Http.HttpGet]
public AjaxAnswer BatchUserCreate(string email, string names) {
string[] emaillist = email.Split('\n');
string[] nameslist = names.Split('\n');
foreach(string email in emaillist) {
db.AddParameter("@email",email);
db.AddParameter("@name",name);
int newId = db.ExecuteScalar(userInsQuery);
}
return new AjaxAnswer(newId);
}
答案 0 :(得分:5)
将两个列表压缩在一起
var nameEmailPairs = emaillist.Zip(namelist, (email,name)=>new{email,name});
然后,您可以{em>
答案 1 :(得分:1)
如果您保证这些列表的顺序相同 - 请使用plain for循环:
for(int i=0; i<emaillist.Length; i++) {
string email = emaillist[i];
string name = namelist[i];
...
或者您可以将LINQ与Zip
:
var records = emaillist.Zip(namelist, (email, name) => new {email, name});
foreach(var r in records) {
string email = r.email;
string name = r.name;
...
答案 2 :(得分:1)
尝试将 foreach 循环更改为 for 循环:
[System.Web.Http.HttpGet]
public AjaxAnswer BatchUserCreate(string email, string names) {
string[] emaillist = email.Split('\n');
string[] nameslist = names.Split('\n');
// You should declare "newId" somewhere here
// if you want to return it via "new AjaxAnswer(newId)"
int newId = 0;
// if emaillist and nameslist have diffrent lengths
// let's take minimal length
int n = Math.Min(nameslist.Length, emaillist.Length);
for (int i = 0; i < n; ++i) {
db.AddParameter("@email", emaillist[i]);
db.AddParameter("@name", nameslist[i]);
newId = db.ExecuteScalar(userInsQuery);
}
return new AjaxAnswer(newId);
}
答案 3 :(得分:1)
你应该使用for
循环,这样的东西可以帮助:
[System.Web.Http.HttpGet]
public AjaxAnswer BatchUserCreate(string email, string names) {
string[] emaillist = email.Split('\n');
string[] nameslist = names.Split('\n');
for(int i = 0; i!=emaillist.Length; ++i) {
db.AddParameter("@email", emaillist[i]);
db.AddParameter("@name", nameslist.Length > i ? nameslist[i] : "No name");
int newId = db.ExecuteScalar(userInsQuery);
}
return new AjaxAnswer(newId);
}
答案 4 :(得分:1)
如果两个数组(emaillist和amplist)的长度相等,则应使用for循环而不是foreach循环:
[System.Web.Http.HttpGet]
public AjaxAnswer BatchUserCreate(string email, string names) {
string[] emaillist = email.Split('\n');
string[] nameslist = names.Split('\n');
for(int i = 0; i < emaillist.Length; i++) {
db.AddParameter("@email",emaillist[i]);
db.AddParameter("@name",namelist[i]);
int newId = db.ExecuteScalar(userInsQuery);
}
return new AjaxAnswer(newId);
}
答案 5 :(得分:1)
尝试这项工作希望它会有所帮助
for(int i =0 ; i< emaillist .count; i++)
{
db.AddParameter("@email",emaillist[i]);
db.AddParameter("@name",nameslist[i]);
int newId = db.ExecuteScalar(userInsQuery);
}