使用数组c#中的值过滤数据表

我有一个删除方法,它获取一个GUID数组,我有一个数据表…我怎样才能过滤数据表,所以它只包含引号?

public void delete(Guid[] guidlist) { datatable template = ReadTemplateList() ... } 

谢谢!

使用Linq to DataSet,您可以创建新的DataTable ,它只包含具有这些Guids的行:

 public void Delete(Guid[] guids) { DataTable table = ReadTemplateList() .AsEnumerable() .Where(r => guids.Contains(r.Field("ColumnName"))) .CopyToDataTable(); // ... } 

另一个选项(也适用于旧的.NET版本)是使用支持INfilter的内置RowFilterfunction过滤您的表。 假设您按名为ID的列进行过滤:

 // Check if guids.Length > 0 StringBuilder filter = new StringBuilder("ID IN ("); foreach (Guid id in guids) filter.AppendFormat("Convert('{0}','System.Guid'),", id); filter.Append(")"); DataTable template = ReadTemplateList(); DataView view = template.DefaultView; view.RowFilter = filter.ToString(); DataTable table = view.ToTable(); 

您可以使用LINQ:

 public static DataTable DeleteGuidsFromTemplate(Guid[] guidlist) { DataTable template = ReadTemplateList(); var rowsWithGuids = from row in template.AsEnumerable() join guid in guidlist on row.Field("Guid") equals guid select row; return rowsWithGuids.CopyToDataTable(); } 

如果你不能使用LINQ,因为你低于NET 3.5:

 public static DataTable DeleteGuidsFromTemplate(Guid[] guidlist) { DataTable template = ReadTemplateList(); DataTable templateGuids = template.Clone(); foreach(DataRow row in template.Rows) { Guid guid = (Guid)row["Guid"]; int index = Array.IndexOf(guidlist, guid); if (index >= 0) templateGuids.ImportRow(row); } return templateGuids; } 

基于DataTableDataRows解决方案。

  //fill the datatable from back end string connStr = ConfigurationManager.ConnectionStrings["ConsoleApplication1.Properties.Settings.NORTHWNDConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); conn.Open(); SqlCommand comm = new SqlCommand("select categoryid,categoryname from Categories order by categoryname"); comm.Connection = conn; SqlDataReader dr = comm.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(dr); //datatable filter logic string[] filter = { "1", "2" }; DataTable filteredTable = dt.Clone(); foreach (string str in filter) { DataRow[] filteredRows = dt.Select("categoryid="+ str); //search for categoryID foreach (DataRow dtr in filteredRows) { filteredTable.ImportRow(dtr); } } 

编辑

没有进入for loop

 DataTable dt = new DataTable(); dt.Load(dr); //fill the datatable with sqldatareader DataTable filteredTable = dt.Clone(); DataView dv = dt.DefaultView; dv.RowFilter = "categoryid in (1,2)"; filteredTable = dv.ToTable();