How to remove particular value from data table in .net

时间:2016-04-04 18:07:39

标签: c# .net linq datatable

I want to remove a particular value from data table ,not like particular row or column,Suppose i have data table as shown below

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

and i have file named age.txt which contains values 23,26,27.So if any of the three values coming in datatable column age,just clear that value, not clear particular row or column.How can i achieve this?

3 个答案:

答案 0 :(得分:2)

I am assuming that your file contains all the ages in a single line of text and your Age field is of integer type

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
}

答案 1 :(得分:1)

You can iterate over the rows in the datatable and set the value to 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;
}

答案 2 :(得分:0)

See this answer. Then simply check the value being inserted and change as necessary.