How to Remove Loop using linq RRS feed

  • Question

  • I have some code and i want to remove foreach loop from my code in linq any possible way ?? please suggest me those way or salution 


            static public string table2Json(DataSet ds, int table_no)
                    object[][] tb = new object[ds.Tables[table_no].Rows.Count][];
                    int r = 0;
                    foreach (DataRow dr in ds.Tables[table_no].Rows)
                        tb[r] = new object[ds.Tables[table_no].Columns.Count];
                        int col = 0;
                        foreach (DataColumn column in ds.Tables[table_no].Columns)
                            tb[r][col] = dr[col];
                            if ((tb[r][col]).Equals(System.DBNull.Value))
                                tb[r][col] = "";
                    string table = JsonConvert.SerializeObject(tb, Formatting.Indented);
                    return table;
                catch (Exception ex)
                    throw ex;

    Tuesday, October 22, 2019 5:19 AM

All replies

  • You can use a for loop instead of a foreach loop, but regardless of the loop type you use,  a loop must be used to iterate and access items in a list or an array.  

    And besides, in what you are doing in looping of rows and columns in a row, you're not even using Linq.

    Tuesday, October 22, 2019 8:33 AM
  • I would not consider using Linq, but changing foreach loop to for loop you can simplity the code a bit.

    int rowCount = ds.Tables[table_no].Rows.Count;
    object[][] tables = new object[rowCount][];
    for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
        DataRow row = ds.Tables[table_no].Rows[rowIndex];
        tables[rowIndex] = new object[row.Table.Columns.Count];
        for (int columnIndex = 0; columnIndex < row.Table.Columns.Count; columnIndex++)
            tables[rowIndex][columnIndex] = DBNull.Value.Equals(row[columnIndex]) ? "" : row[columnIndex];

    Wednesday, October 23, 2019 11:55 AM
  • Why? What is wrong with a foreach loop? You are modifying data within the inner foreach loop. You're going to have to keep that as LINQ is query only, unless you're projecting data to something else.

    Looking at the code it appears you're trying to take a DataTable and convert it to an array of arrays where each cell is stored so you can serialize. (DB)nulls are converted to empty strings. Not sure the benefit of this as you're going to end up with a structure that doesn't resemble the original data anymore and likely isn't even going to be easily deserializable back from JSON.

    //Assume table structure - Id (int), Name (string), Rate (double)
    dr["Id"] = 10;
    dr["Name"] = "Bob";
    dr["Rate"] = 8.25;
    //As an array you were trying to build
    tb = new object[][] {
       new object[] { 10, "Bob", 8.25 }
    //Serialized to JSON

    There isn't going to be an easy way to read this back as you have an array of arbitrary data which doesn't make a lot of sense. At a minimum you would expect to be able to serialize out a custom object that has field names for your columns.

          "Id": 10,
          "Name": "Bob",
          "Rate": 8.25 
    This can be done using LINQ and makes more sense to me.

    Michael Taylor

    Wednesday, October 23, 2019 1:54 PM
  • Hi Sanjay8090,

    Thank you for posting here.

    For your question, you want remove Loop by using linq.

    In fact, in order to achieve your function, the loop is inevitable, but I simplified your code with linq.

    Here is my code:

    public static string table2Json(DataSet ds, int table_no) { try { DataTable dataTable = ds.Tables[table_no]; var nullValues = dataTable.AsEnumerable().Where(row => row.ItemArray.Any(v => v is DBNull)); foreach (var item in nullValues) { for (int i = 0; i < item.ItemArray.Length; i++) { item[i] = item[i].Equals(DBNull.Value)? "" : item[i]; } } string table = JsonConvert.SerializeObject(dataTable, Formatting.Indented); return table; }

      catch (Exception ex)
                    throw ex;

    Hope my solution could be helpful.

    Best regards,

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Thursday, October 24, 2019 3:17 AM