Reputation: 19163
I have a Dataset containing one DataTable and that table got 3 columns (Column1,Data,Column2) & multiple data-rows.
I also have a dictionary which contains list of values that I need to search within DataColumn and the values with which I should replace the original values.
I want to search with-in the column whose name is 'Data'.
Following image contains the original data table and the resultant DataTable along with dictionary which contains keys and values which needs to be searched and replaced.
What is the most efficient way to perform this operation?
Upvotes: 1
Views: 8038
Reputation: 216263
I am sure that there is best way to do this using LinQ, but this will do
Dictionary<string,string> dic = new Dictionary<string,string>();
dic.Add("AAA", "A++");
dic.Add("BBB", "B++");
foreach(KeyValuePair<string, string> kvp in dic)
{
DataRow[] sl = dt.Select("DATA='" + kvp.Key + "'");
foreach(DataRow r in sl)
r["DATA"] = kvp.Value;
}
The inner foreach loop could be replaced by the expression
sl.ToList().ForEach(x => x.SetField<string>("DATA", kvp.Value));
but I haven't tested for performance
Probably is not very efficient for large sets of data, but a thing that should be considered is to loop on dictionary Keys and not on the single rows of the table.
Upvotes: 1
Reputation: 11
I would handle it like this:
DataSet ds = new DataSet();
string strNewXmls = ds.GetXml().Replace("AAA", "A++");
System.IO.StringReader srXmlStringReader = new System.IO.StringReader(strNewXmls);
ds.ReadXml(srXmlStringReader, XmlReadMode.IgnoreSchema);
This is a quick and simple solution. You can do this with every kind of stuff in your whole DataSet.
Hope it helps,
Taragneti
Upvotes: 0
Reputation: 38179
Go for simplicity
foreach (DataRow row in dataSet.Tables[0].AsEnumerable())
{
string data = row.Field<string>("Data");
string newData = null;
if (dict.TryGetValue(data, out newData))
{
row.SetField("Data", newData);
}
}
(you'll need to add System.Data.DataSetExtensions to your project references)
Upvotes: 0