Share via


Replace specific column values in C# datatable without using any loops?

Question

Tuesday, September 11, 2012 5:13 AM

Sir,

     I Have a datatable as follows

              ID      Name    Result

               1       Anu       86

               2      Ajay       56

               3      Manu      86

Here  for column Result , I need to replace 86 with passed and all values expect 86 with failed without any looping .Please tell me how can i do that using C#

All replies (3)

Tuesday, September 11, 2012 6:37 AM âś…Answered | 1 vote

Considering your requirement, I think you will end up in using loop directly or indirectly. Also, you might have to change datatype of Result column to string if it's not originally so (it seems to be integer from vlaues). Considering all this, I would rather suggest addition of another column which uses expression based syntax to determine it's values based on values in Result column. So, you can do something like following:

DataColumn resultStatus = new DataColumn();            resultStatus.DataType = System.Type.GetType("System.String");            resultStatus.ColumnName = "ResultStatus";            resultStatus.Expression = "IIF(Result = 86, 'Passed', 'Failed')";            table.Columns.Add(resultStatus);

This will help you in avoiding looping as well as preserving your original Result column in case you need it's contents in future.

HTH

Sameer

If this answers your question, please Mark it as Answer. If this post is helpful, please vote as helpful.


Tuesday, September 11, 2012 9:54 AM

i think LINQ is most useful in this process . you  use Linq and perform this task easyly

software ->Dev


Tuesday, September 11, 2012 11:15 AM

You can go for CTE(common table expressions) and use Case to select values based on your column values.

If you just want to query the result then use this else if you want to change the actual value in the table then need to select the new values using the above CTE and then storing it into temporary table.

Mark it as helpful if so!!! thanks, Mithilesh