【问题标题】:How to remove particular value from data table in .net如何从.net中的数据表中删除特定值
【发布时间】:2016-07-24 09:59:38
【问题描述】:

我想从data table 中删除一个特定的值,而不是特定的行或列,假设我有如下所示的数据表

======================================================
| firstname  |     lastname  |     age  |   location |
======================================================
| Jhonson    |    charles    |      32  | dever      | 
| Jaques     |    kallis     |      33  | cevek      |
| rama       |    kalyani    |      23  | qwet       |
| sasi       |    kiran      |      22  | delli      |
======================================================

我有一个名为 age.txt 的文件,其中包含值 23、26、27。因此,如果数据表列 age 中的三个值中的任何一个,只需清除该值,而不是清除特定的行或列。我怎么能实现这个?

【问题讨论】:

  • 这些年龄值都在单行逗号分隔或在单独的行?

标签: c# .net linq datatable


【解决方案1】:

请参阅this 答案。然后只需检查插入的值并根据需要进行更改。

【讨论】:

    【解决方案2】:

    您可以遍历数据表中的行并将值设置为 null。

    // Split the text values into an array of strings
    string[] checkAgeArray = "23,26,27".Split(',');
    
    DataTable person;
    
    foreach (var row in person.Rows)
    {
        // Compare the string ages to the string value of the integer age in table
        if (checkAgeArray.Contains(row["age"].ToString()))
            row["age"] = System.DBNull;
    }
    

    【讨论】:

    • 出错“无法使用对象的 [] 表达式类型应用 indexint”为什么?
    【解决方案3】:

    我假设您的文件在一行文本中包含所有年龄,并且您的年龄字段是整数类型

    DataTable dt = LoadYourTable();
    string agesData = File.ReadAllText("age.txt");
    
    // Create an array of the ages  integer loaded from your file
    int[] ages = agesData.Split(',').Select(x => Convert.ToInt32(x)).ToArray();
    
    // Loop over the rows collection
    foreach(DataRow r in dt.Rows)
    {
        // If the ages array contains the Age value of the current row
        if(ages.Contains(r.Field<int>("Age")))
           r.SetField<int>("Age", 0);  // Or set it to DBNull.Value
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      相关资源
      最近更新 更多