代码之家  ›  专栏  ›  技术社区  ›  Churchill

如何跳过sqldatareader中的第一行

c#
  •  3
  • Churchill  · 技术社区  · 15 年前

    我正在从数据库中检索10行,但我想跳过第一个。原因是我的表中的第一项已经显示在我的页面的主div中。现在我要列出它下面的所有其他记录。我如何做到这一点?

    我的代码工作正常,我可以显示阅读器中的所有记录。我现在只需要跳过第一个。

    4 回复  |  直到 15 年前
        1
  •  13
  •   Oded    15 年前

    myReader.Read();
    
    while(myReader.Read())
    {
       //do stuff
    }
    
        2
  •  10
  •   Thomas Levesque    15 年前

    如果您喜欢使用Linq,这里有一个技巧,可以使用一个简单的扩展方法使它与DataReaders一起工作:

    public static IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)
    {
        while (reader.Read())
        {
            yield return reader;
        }
    }
    

    Skip 方法:

    using (var reader = command.ExecuteRead())
    {
        foreach(var row in reader.AsEnumerable.Skip(1))
        {
            // whatever you do with the data...
        }
    }
    
        3
  •  1
  •   Jon Skeet    15 年前

    打个电话就行了 reader.Read() reader.Read() false 那就连你期待的第一张唱片都没有了。

        4
  •  0
  •   carlsb3rg    15 年前

    • 也许您的SQL查询、存储过程或其他什么应该排除第一行?
    • 你为什么已经有第一排了?也许你可以同时得到所有的行?

    您的问题意味着缺乏编码经验-无论是在一般情况下,还是关于DataReader或其他方面。如果你解释一下为什么要跳过第一排,也许你能得到更多的帮助?