如何做,在复杂的数据表上手动过滤操作



我在家庭控制器中有一个数据表,如下:

public DataTable GetTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(Info));
    table.Columns.Add("Date", typeof(DateTime));
    table.Rows.Add(25, "Indocin", new Info("India"), DateTime.Now);
    table.Rows.Add(50, "Enebrel", new Info("UK"), DateTime.Now);
    table.Rows.Add(10, "Hydralazine", new Info("Bhutan"), DateTime.Now);
    table.Rows.Add(21, "Combivent", new Info("India"), DateTime.Now);
    table.Rows.Add(100, "Dilantin", new Info("GreenLand"), DateTime.Now);
    return table;
}

信息类如下

public class Info
{
    public string Address { get; set; }
    public Info(string Add) {
        this.Address = Add;
    }
}

现在,我想根据地址字段进行过滤操作,即患者。address

在这里,患者是信息类的对象

我获取了有关每列的信息,如下所示,我已经在" datatablextensions.datatapableserialize(data)"方法中定义了功能

DataTableExtensions.DataTableSerialize(data)
Count = 4
    [0]: {[Dosage, System.Nullable`1[System.Int32]]}
    [1]: {[Drug, System.String]}
    [2]: {[Patient, MvcApplication66.Controllers.HomeController+Info]}
    [3]: {[Date, System.Nullable`1[System.DateTime]]}

,但是,我需要根据患者过滤数据表

我在以下行中遇到了错误。

DataTableExtensions.DataTableSerialize(data)[ColumnName]

类型的未经手的例外 'System.Collections.generic.KeyNotFoundException'发生在 mscorlib.dll

附加信息:给定的键不存在 字典。

我在哪里犯错。

是否可以在复杂数据表中进行过滤操作。

复杂的数据表可以过滤,我为此要求形成了谓词。

var memberNames = memberPath.Split('.');
Expression value = Expression.Call(
    typeof(DataRowExtensions), "Field", new Type[] { columnType },
    source, Expression.Constant(memberNames[0]));
for (int i = 1; i < memberNames.Length; i++)
    value = Expression.PropertyOrField(value, memberNames[i]);
return value;

最终形成的谓词bexp = {(datarow.field(" detter")。地址.tolower()=="印度")}

所以,查询字符串将为data = {system.data.enumerablerowCollection`1 [system.data.datarow] .where(datarow =>(datarow =>)

现在,我能够获取数据。

有关更多详细信息:请参阅以下链接

如何使用Express.call方法

创建(谓词)以获取数据的数据(谓词)

您可以使用Linq

过滤数据表
//fill the datatable
DataTable dt = GetTable();
//filter the datatable with Linq
var filteredRows = dt.AsEnumerable().Where(x => x.Field<Info>("Patient").Address == "India");
//check if there are any rows before calling CopyToDataTable,
//otherwise you'll get a "The source contains no DataRows" error
if (filteredRows.Any())
{
    DataTable dtFiltered = filteredRows.CopyToDataTable();
}

如果您100%确定过滤表包含行,则可以直接调用CopyToDataTable()

DataTable dtFiltered = dt.AsEnumerable().Where(x => x.Field<Info>("Patient").Address == "Bhutan").CopyToDataTable();

,但我建议您从DataTable到列表中的Swich,将来Info变得更加复杂会更容易。

List<Drugs> patients = new List<Drugs>();
public class Drugs
{
    public int Dosage { get; set; }
    public string Drug { get; set; }
    public Info Patient { get; set; }
    public DateTime Date { get; set; }
}

最新更新