使用字符串值的c#数据表过滤器

本文关键字:数据表 过滤器 字符串 | 更新日期: 2023-09-27 18:04:11

我正试图实现另一个要求,在我有数据表中的数据,如下所示

DataTable tableold = new DataTable();
tableold.Columns.Add("Dosage", typeof(string));
tableold.Columns.Add("Drug", typeof(string));
tableold.Columns.Add("Patient", typeof(string));
tableold.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
tableold.Rows.Add(#25, "Indocin", "David", DateTime.Now);
tableold.Rows.Add(#50, "Enebrel", "Sam", DateTime.Now);
tableold.Rows.Add(#10, "Hydralazine", "Christoff", DateTime.Now);
tableold.Rows.Add(#21, "Combivent", "Janet", DateTime.Now);
tableold.Rows.Add(#100, "Dilantin", "Melanie", DateTime.Now);

现在我有一个字符串数组如下所示

string[] values; (which contains {#25, #50, #10} values)

我需要删除tableold(基表)中存在于字符串数组中的值。(我知道我问这个问题很尴尬,但我是新手)

所以我需要更新数据表(tableold)看起来像这样:

21, "Combivent", "Janet", "10:20:00"
100, "Dilantin", "Melanie", "10:20:00"

如何用c#或LinQ编写这样的查询

请帮忙!由于

使用字符串值的c#数据表过滤器

With LINQ:

var newRows = tableold.AsEnumerable().Where(r => !values.Contains(r.Field<string>("Dosage")));
if(newRows.Any())
    tableold = newRows.CopyToDataTable();
else
    tableold = tableold.Clone(); // empty

问题有点不清楚,我从输出中理解您想要排除一些ids。你可以这样做,使用Linq

// list of Ids to exclude
var ids = new List<int>() {25, 50, 10};
// filter table.    
var newTable = tableold.AsEnumerable()
        .Where(x=> !ids.Contains(x.Field<int>("Dosage")))
        .CopyToDataTable();

Check this demo