如何在 C# 中转换具有特定结构的 table 中的 sqldatareader?

How to convert an sqldatareader in a table with specific structure in C#?

我有一个 SQLDatareader return 格式的数据:

58, A1
59, A2
60, A3
61, A4
62, B1
63, B2
64, B3
65, B4
66, C1
67, C2
68, C3
69, C4
70, D1
71, D2
72, D3
73, D4

这可以继续进行以获取更多记录。 我想 return 那些顺序不同的(两个字段)。像这样:

58, A1
62, B1
66, C1
70, D1
59, A2
63, B2
67, C2
71, D2
61, A3
64, B3
68, C3
72, D3
61, A4
65, B4
69, C4
73, D4

有办法吗?

提前谢谢你, 季米特里斯

如前所述here:

A SqlDataReader class:

Provides a way of reading a forward-only stream of rows from a SQL Server database.

也就是说,如果您不想更改您的sql声明如果您不允许这样做,你应该先把你的结果存储在内存中,然后再做你想要的。

一个选项是定义一个 class,如下所示:

// The name of the class is vague. Not knowing
// what your data represent, is quite difficult to 
// give a proper name.
public class Result
{
    public int Number  { get; private set; }
    public string Text { get; private set; }

    public Result(int number, string text)
    {
        Number = number;
        Text = text;
    }
}

然后我会定义一个类型为 Result:

的对象列表
var results = new List<Result>();

while 循环中读取数据后,我会在每个循环中创建一个 Result:

类型的对象
var result = new Result(..,...);

然后我们将其添加到 results 列表中。

最后您将得到一个包含 Result 个对象的列表,您可以根据需要对其进行排序。使用 LINQ.

可以很容易地完成此操作
var results = results.OrderBy(result=>result.Text[1]).ToList();

你可以看看上面这个.NET Fiddle