5

我在 DataSet 中有一个表,我想使用唯一键在此表中搜索一行。

我的问题是:有没有什么方法可以让我在不使用循环的情况下找到这一行?

这是我使用 forech 循环编写的代码:

foreach (var myRow in myClass.ds.Tables["Editeur"].AsEnumerable())
{
     if (newKeyWordAEditeurName == myRow[1] as String)
         id_Editeur_Editeur = (int)myRow[0];
}
4

2 回答 2

15

当然。您有一个 DataTable 的 Select 方法。从您的 DataSet 中获取表,并使用 Select 来获取它。

void Demo(DataSet ds)
{
    DataTable dt = ds.Tables[0]; // refer to your table of interest within the DataSet

    dt.Select("Field = 1"); // replace with your criteria as appropriate
}
于 2012-09-29T21:16:29.243 回答
0

要查找特定行,您可能需要按可以唯一标识每一行的键进行搜索。
但是如果你想找到一组行,那么你想使用过滤器。

键可以同时包含不同类型的对象。所以可以过滤!

下面是一个具体的例子,它涵盖了使用 key 方法或 filter 方法分别作为 locateOneRow() 和 locateRows() 进行搜索。

using System.Data;
namespace namespace_A {
  public static class cData    {
     public static DataTable srchTBL = new DataTable(tableName: "AnyTable");
     public static DataColumn[] theColumns = {
     new DataColumn("IDnum", typeof(int))
     , new DataColumn("IDString", typeof(string))
     , new DataColumn("DataString", typeof(string))
     };
     public static void DataInit(){
        if (srchTBL.Columns.Count == 0) {
           srchTBL.Columns.AddRange(theColumns);
           srchTBL.PrimaryKey = new DataColumn[2] { srchTBL.Columns["IDnum"], srchTBL.Columns["IDstring"] };
        //Data
           srchTBL.Rows.Add(0, "me", "Homemaker");
           srchTBL.Rows.Add(1, "me2", "Breadwinner2");
           srchTBL.Rows.Add(1, "you", "Breadwinner1");
           srchTBL.Rows.Add(2, "kid", "Learner");
        }
     }//DataInit
     public static DataRow locateOneRow(){
        DataInit();
        object[] keyVals = new object[] {0, "me" };
        return srchTBL.Rows.Find(keyVals);
     }//locateOneRow - Result: the "Homemaker" row
     public static DataRow[] locateRows(){ //no Primary key needed
        DataInit();
        return srchTBL.Select("IDnum = 1 OR IDstring = 'me'");
     }//locateRows - Result: the row with "Homermaker" & the row with "Breadwinner2"  
   }//class
   class Program    {
      static void Main(string[] args)       {
      try
      {
          DataRow row1 =cData.locateOneRow();
          DataRow[] rows = cData.locateRows();
      }catch(Exception ex){
     
      }
    } // Main
  } // Program
}
于 2021-12-16T17:47:57.580 回答