Posted by: R Manimaran | March 17, 2014

Change Data Table column values using Lambda expression

Change Data Table column values using Lambda expression

I have a resulted Data Table in which I need to replace all the values in a column. After replacement I need to create the DataTable again.

I have used a SharePoint list for this example. I have a list Project Contacts which contains a country column and below are the values.

I need to change all the value in the Work Country to “India”. I have used below Lambda expression to change the values.


SPQuery query = new SPQuery();

query.ViewFields= @"<FieldRef Name='Title' /><FieldRef Name='WorkCountry' />";

DataTable dt = list.GetItems(query).GetDataTable();

dt.Rows.Cast<DataRow>().ToList().ForEach(r=>r.SetField("WorkCountry","India"));

In the other case, I need to change the relevant values based on the Country values.

SPQuery query = new SPQuery();
query.ViewFields= @"<FieldRef Name='Title' /><FieldRef Name='WorkCountry' />";
DataTable dt = list.GetItems(query).GetDataTable();
dt.Rows.Cast<DataRow>().ToList().ForEach(r => r.SetField("WorkCountry", GetCountry(r["WorkCountry"].ToString())));</span>

 //Method to return Country name
 public static string GetCountry(string twoletter)
 {
 string country=string.Empty;
 if (!string.IsNullOrEmpty(twoletter))
 {
 switch (twoletter)
 {
 case "IN":
 country = "India";
 break;
 case "CA":
 country = "Canada";
 break;
 case "US":
 country = "United States";
 break;
 }
 }
 return country;
 }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: