从列表中删除重复项,但保留其计数

时间:2015-08-26 06:33:29

标签: c# sql asp.net sql-server asp.net-mvc

我试图将(未知数量)多个值放入数据库中(使用ASP.NET MVC - C#),创建如下查询:

INSERT INTO [dbo].[names](name, lastname) 
VALUES ("Foo", "Bar"), 
       ("John, "Smith"),
       ("Var", "Dar")

在C#代码中看起来像这样:

//conn is an SqlConnection object
using (var cmd = conn.CreateCommand())
{
    cmd.CommandText = @"INSERT INTO [dbo].[names](name, lastname) VALUES ";
    //The reason it goes backwards is because this is only simplified insert query,
    //real query also does some sorting, which does Not cause the issue.
    for (int i = articleFullList.Count - 1; i > 0; i--)
    {
        cmd.CommandText += "(@firstname" + i + ", @lastname" + i + ")";
        if(i > 0)
            cmd.CommandText += ", ";
        cmd.Parameters.AddWithValue("@firstname" + i, someFirstNameValue);
        cmd.Parameters.AddWithValue("@lastname" + i, someLastNameValue);
    } 
}

但我总是得到一个

  

附近的语法错误

错误,但如果我删除if(i> 0)语句(及其下面的行),我会收到类似的错误

  

@ firstname1

附近的语法错误

感谢阅读!

1 个答案:

答案 0 :(得分:3)

循环必须继续,直到达到零:

for (int i = articleFullList.Count - 1; i >= 0; i--)