Narasiman nar

Narasiman nar

  • NA
  • 64
  • 22.1k

Validate dict value is empty in c#

May 28 2018 11:36 PM
Id Name farmdetailsdata
1 Test1 {"Product1":"A","Product2":"B"}
2 Test2
3 Test3 {"Product1":"C","Product2":"D"}
i am validating dict value is empty using below code
  1. int columnindex = 43;  
  2. List<string> lst = new List<string>();  
  3. foreach (DataRow row in dtFarmerFarmReports.Rows)  
  4. {  
  5. var dict = JsonConvert.DeserializeObject<Dictionary<stringstring>>(row["farm_detailsdata"].ToString());  
  6. if (dict != null)  
  7. {  
  8. lst.AddRange(dict.Keys);  
  9. }  
  10. }  
  11. var distinctList = lst.Distinct().ToList();  
  12. List<ExcelHeader> excelheaderlist = new List<ExcelHeader>();  
  13. foreach (var data in distinctList)  
  14. {  
  15. columnindex++;  
  16. worksheet.Cells[2, columnindex].Value = data;  
  17. ExcelHeader excelHeader = new ExcelHeader  
  18. {  
  19. colIndex = columnindex,  
  20. colName = data  
  21. };  
  22. excelheaderlist.Add(excelHeader);  
  23. }  
  24. foreach (var dicdata in dict)  
  25. {  
  26. int colval = excelheaderlist.Where(x => x.colName == dicdata.Key).Select(y => y.colIndex).FirstOrDefault();  
  27. if (colval > 0)  
  28. {  
  29. worksheet.Cells[(j1), colval].Value = dicdata.Value;  
  30. }  
  31. }  
from the above validating null value using dict. when i run the above i get error as follows
 
object reference not set to an instance of object. This error shows in below line as follows
 
foreach (var dicdata in dict).
 
how to fix this error. from my above code what changes i have to make.

Answers (1)