簡體   English   中英

從數據表中選擇一列以檢查其值

[英]Selecting a column from datatable to check its values

我有一個數據表,它有 3 列“名稱”、“類型”、“ID”,我只想使用其中的一列進行比較。 這是“類型”。 我想將該列放在與數據表分開的 DataColumn 中,將其中單元格的值與字符串進行比較,如果匹配則傳遞一個字符串。 我不確定這種方法是對還是錯,我什至不知道如何獲取要比較的此 Datacolumn 中單元格(行)的字符串值

這是我的代碼:

DataTable Griddetails;
Griddetails = RxMUaClient.BrowseGrid("2", "127.0.0.1:48030", nodepassed);

var myColumn = Griddetails.Columns.Cast<DataColumn>()
                          .SingleOrDefault(col => col.ColumnName == "Type");

return Json(myColumn);
if (myColumn != null)
{
    for (int i = 0; i <= myColumn.; i++ )
    {

    }
}

我試圖通過 for 循環或 foreach 獲取 dataColumn 中的數據行計數,foreach 對某些錯誤不起作用,我不知道如何獲取 for 循環的數據列的值。

有什么幫助嗎?

即使這個問題對我來說仍然沒有多大意義,如果您只想知道一個表有多少行屬於給定的DataColumn

int rowCount = myColumn.Table.Rows.Count;

請注意,您不需要 LINQ 查詢來查找列,您可以使用采用字符串DataColumnCollection 索引器

DataColumn myColumn = Griddetails.Columns["Type"];

如果沒有具有該名稱的列並返回null ,它會按需要工作。


在您編輯的問題之后,您似乎實際上想要找到包含給定值的類型列的行。 您可以使用 LINQ:

var matchingRows = from row in Griddetails.AsEnumerable()
                   where row.Field<string>("Type") == valueYouSearch
                   select row;

DataRow firstRow = matchingRows.FirstOrDefaul();
if(firstRow != null)
{
    // here you know that there is at least one row with that value in the type-column
    string firstType = firstRow.Field<string>("Type"); // pointless, maybe you want to return different column's value
    // ....
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM