使用c#从Datatable中检索特定行

时间:2013-10-24 08:21:14

标签: c# json vb.net datatable

我在我的应用程序中创建了一个数据表

DataTable table = new DataTable();

它具有以下格式

    ID    |  Name     |  Add    |   Edit  | View   | Authorize
    ---------------------------------------------------------------------
    10    | User      | true    |  trues  | trues  |  true
    11    | Group     | true    |  trues  | trues  |  true
    12    | Permission| true    |  trues  | trues  |  true

我想通过id从这个数据表中检索一行。

例如,我想检索id = 12

即,

  12    | Permission| true    |  trues  | trues  |  true

之后我想使用json.net

仅将此行转换为json字符串
{["id":"12","name":"Permission","add":true,"edit":true,"authorize":true,"view":true}]

有可能吗?请帮忙

2 个答案:

答案 0 :(得分:2)

您可以使用LINQ和Json.NET。 在您的课程顶部添加:

using System.Linq;

在您的代码中,您可能有两种方法:

// 1. select the row in the table
// 2. create an anonymous object
// 3. serialize it
var json1 = JsonConvert.SerializeObject(table.Select("ID=12")
    .Select(row => new
    {
        id = row["ID"],
        name = row["Name"],
        add = row["Add"],
        edit = row["Edit"],
        view = row["View"],
        authorize = row["Authorize"]
    }).FirstOrDefault());

// 1. cast all rows in the table
// 2. create a collection of anonymous objects
// 3. select the anonymous object by id
// 4. serialize it
var json2 = JsonConvert.SerializeObject(table .Rows
    .Cast<DataRow>()
    .Select(row => new
    {
        id = row["ID"],
        name = row["Name"],
        add = row["Add"],
        edit = row["Edit"],
        view = row["View"],
        authorize = row["Authorize"]
    })
    .FirstOrDefault(row => row.id.ToString() == "12"));

或者,您可以使用自己的班级。此选项不一定需要LINQ:

// 1. select the row
// 2. create a new TableRow object
// 3. serialize it
var filteredRow = table.Select("ID=12");
if (filteredRow.Length == 1)
{
    var json3 = JsonConvert.SerializeObject(
        new TableRow(filteredRow[0].ItemArray));
}

简化的TableRow类定义可能如下所示:

public class TableRow
{
    public int id { get; set; }
    public string name { get; set; }
    public bool add { get; set; }
    public bool edit { get; set; }
    public bool view { get; set; }
    public bool authorize { get; set; }

    public TableRow(object[] itemArray)
    {
        id = Int32.Parse(itemArray[0].ToString());
        name = itemArray[1].ToString();
        add = bool.Parse(itemArray[2].ToString());
        edit = bool.Parse(itemArray[3].ToString());
        view = bool.Parse(itemArray[4].ToString());
        authorize = bool.Parse(itemArray[5].ToString());
    }
}

答案 1 :(得分:0)

如何使用DataTable

Select方法
DataRow[] dr = table.Select("id = 12");

或者是动态的

int rowid = ... //assign some value through code and then
DataRow[] dr = table.Select("id = " + rowid);

我不知道JSON,但你可以看看

Convert DataTable to JSON with key per row
http://www.codeproject.com/Tips/624888/Converting-DataTable-to-JSON-Format-in-Csharp-and
C# DataTable to Json?