1

My datatable looks like

Id|Name|Status
1 |a   |1
2 |b   |1
3 |c   |1
4 |d   |1

and dictionary have key value pair like

key Value
2    y 
4    Y

dictionary will contain only those keys whose status need to be updated

and the updated datatable that i need is something like below,

Id|Name|Status
    1 |a   |1
    2 |b   |0
    3 |c   |1
    4 |d   |0

So is this achievable in c# using linq.

abhi
  • 1,059
  • 9
  • 19
  • What is the logic you want, to set the status of anything in the Dictionary to 0 in the database? – Karl Gjertsen Jan 26 '16 at 14:57
  • 1
    Linq on its own cannot update the database, how are you connecting to the database? Some sample code you have tried so far would help us to help you. – Karl Gjertsen Jan 26 '16 at 14:58
  • So, everything in the dictionary must be updated, or is a pair like (1, n) possible? – Aaron Gates Jan 26 '16 at 14:58
  • @KarlGjertsen it dose not matter what's the value in Dictionary, if key is there in Dictionary its corresponding status has to be changed in datatable, and one more thing if linq can not update data table then is it possible to insert these updated value in new data table – abhi Jan 26 '16 at 15:02
  • @AaronGates yes every key in dictionary needs to be updated in data table – abhi Jan 26 '16 at 15:04
  • @abhi *Updated* means assign `0` ? – tchelidze Jan 26 '16 at 15:06
  • You should take a look at [Use linq to generate direct update without select](http://stackoverflow.com/questions/445033/use-linq-to-generate-direct-update-without-select) which possibly may 'partly' be a duplicate to your question. – Dbuggy Jan 26 '16 at 15:07
  • @tchelidze yes it does – abhi Jan 26 '16 at 15:07
  • What is the logic for the update? Does the value in the database need setting to 0 if the Database ID is the key in the dictionary? – Karl Gjertsen Jan 26 '16 at 15:08
  • @abhi you can get all records which needs to be updated with following query. then loop thru each one and assign 0 to `Status` Property. `datatable.Where(dt => dict.Any(di => di.Key == dt.Id))` – tchelidze Jan 26 '16 at 15:10
  • @KarlGjertsen yes if datatable ID matches any key available in dictionary, its value needs to be updated and by update means we can have new datatable – abhi Jan 26 '16 at 15:14

1 Answers1

1

I was able to get this to work, if I understand what you're wanting to do correctly. Someone else may have a more elegant solution, but this is working...

oDt.Select(string.Format("[Id] in ({0})",string.Join(",",oDict.Select(x=>x.Key)))).ToList<DataRow>().ForEach(r=>r["Status"] = 0);

where oDt is your datatable, and oDict is your dictionary.

Aaron
  • 1,313
  • 16
  • 26
  • awesosme man, its the most unique answer i saw for this sort of query, If you can add little description of what is happening here, it can help others a lot – abhi Jan 27 '16 at 06:58