0

In my Sp, which returns only one record always. I need to take the values of each column to separate variable. I did as follows (part of my c#),

DataSet sampleDataTable = DataAccessManager.ExecuteStoredProcedure("spGetUserData", parameters);
string accNo = Convert.ToString(sampleDataTable.Tables[0].Rows[0]["AccountNumber"]);

The above code works fine. I also tried as follows,

string accNo = nonProvidedServices.Tables[0].AsEnumerable().Select(row => row.Field<string>("AccountNumber")).ToString();

But it's not working properly. What is the best and efficient way to assign datatable column value to a string variable? Is Linq query efficient than my working code?

Sachith Wickramaarachchi
  • 5,546
  • 6
  • 39
  • 68
  • First, if it only returns one record, why fill a DataSet, there's no need for that. . `var accNo = nonProvidedServices.Tables[0].Rows.Cast().FirstOrDefault()?.Field("AccountNumber");` – Trevor Feb 12 '20 at 15:41
  • Or `var accNo = nonProvidedServices.Tables[0].AsEnumerable().FirstOrDefault()?.Field("AccountNumber");` this route is a tad better in efficiency. – Trevor Feb 12 '20 at 15:50
  • What is the best way your answer or this (`Convert.ToString(sampleDataTable.Tables[0].Rows[0]["AccountNumber"]);`) – Sachith Wickramaarachchi Feb 12 '20 at 16:02
  • it's not about `best way` if it works, it works, right? TBH, there's not really any performance issue's here, just use what you want; there's more than one way to do something. On another note, if you choose to use your way, it may fail because of rows not existing as well as your convert would fail. – Trevor Feb 12 '20 at 17:14
  • @Çöđěxěŕ And coulmn data is null the your code returns exception. how to handle null – Sachith Wickramaarachchi Feb 12 '20 at 17:55
  • What code are you using? – Trevor Feb 12 '20 at 17:56
  • @Çöđěxěŕ I used `var accNo = nonProvidedServices.Tables[0].AsEnumerable().FirstOrDefault()?.Field("id");` when I column null its returns exception – Sachith Wickramaarachchi Feb 12 '20 at 17:58
  • @Çöđěxěŕ I need to set null for `accNo` is null. otherwise need to set column value – Sachith Wickramaarachchi Feb 12 '20 at 17:59
  • 1
    that's because the type you gave it is non null, so try `nonProvidedServices.Tables[0].AsEnumerable().FirstOrDefault()?.Field("id");` Notice the `?` in `.Field`, this means it can be null and would need to be a nullable type. Also it may be different as you have seen, this isn't the same you posted in your question... – Trevor Feb 12 '20 at 18:00
  • @Çöđěxěŕ Thanks sir – Sachith Wickramaarachchi Feb 12 '20 at 18:22
  • you're welcome, good luck. – Trevor Feb 12 '20 at 19:42

0 Answers0