【问题标题】:Remove duplicates from list, but keep their count numbers从列表中删除重复项,但保留其计数
【发布时间】:2015-08-26 06:33:29
【问题描述】:

我正在尝试将(未知数量)多个值放入数据库(使用 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 附近的语法错误

感谢阅读!

【问题讨论】:

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


    【解决方案1】:

    循环必须持续到零:

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

    【讨论】:

    • 这么简单的解决方案已经很久没见过了……我很惭愧。谢谢@Taher,我会检查一下它是否有效并给你一个积极的评价。
    • 抱歉等待,该解决方案完美运行 :) 这是一个已确认的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多