Creating hierarchical data using closure in C #?




I am trying to create hierarchical data using closure in C #. I have a Method " **Pair** " that looks like this:



```
  public static Func<string, int> Pair(int x,Func<string, int> y)
    {

        Func<string, int> pair =
               (a) =>
               {
                   if (a == "con") return x;
                   if (a == "crd") return y("con");
                   throw new Exception();
               };

        return pair;
    }

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

Than I will create my Hierarchical data as below:



```
      var pair = Pair(1,
                        Pair(2,
                              Pair(3,
                                    Pair(4,null))));

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

 which when visually presented looks like this:
![](https://fooobar.com//img/3e0173c58cb56a30476d9bc98ccb38a5.jpg)


I know this approach is wrong because I cannot get / print all the values ​​stored in a pair. I cannot do something like this:



```
 public static void Print(Func<string, int> pair)
    {
        if (pair("crd") == null) return;
        Console.WriteLine(pair("con"));
        Print(pair("crd")); //Compilation Error
    }

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

Can someone tell me how to do this in C #.
The problem is that your pair's closure must return two different types of objects: int if you ask for "con", and the next closure on the line if you ask for "crd".


Here's one possible implementation:


Use a speaker so you can come back.



```
public static Func<string, dynamic> Pair(int x, Func<string, dynamic> y)
{
    Func<string, dynamic> pair =
           (a) =>
           {
               if (a == "con") return x;
               if (a == "crd") return y;
               throw new Exception();
           };

    return pair;
}

public static void Print(Func<string, dynamic> pair)
{
    while (true)
    {
        var next = pair("crd");
        Console.WriteLine((next == null ? "-":"+") +"> " + pair("con"));
        if (next != null)
        {
            Console.WriteLine("|");
            pair = (x) => next(x);
            continue;
        }
        break;
    }
}

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```


  




 (adsbygoogle = window.adsbygoogle || []).push({});
 
  

Test:



```
var pair = Pair(1,
            Pair(2,
                  Pair(3,
                        Pair(4, null))));

Print(pair);

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```

output:



```
+> 1
|
+> 2
|
+> 3
|
-> 4

        

        
        
        
 (adsbygoogle = window.adsbygoogle || []).push({});
 
        

    
```
How about in c++?



[http://www.1cplusplusstreet.com/vb/scripts/ShowCode.asp?txtCodeId=6877&lngWId=3](/posts/bad_link/258354?url=http%3A%2F%2Fwww.1cplusplusstreet.com%2Fvb%2Fscripts%2FShowCode.asp%3FtxtCodeId%3D6877%26lngWId%3D3) [image] akanksha\_varshney:

(convert.tostring(date\_created\_hs.substring(0,10)).equals(convert.tostring(date\_created\_cchq.substring(0,10)))) or (date\_created\_hs <> “”)

hey,

try with the following one,

(convert.tostring(date\_created\_hs.substring(0,10).trim).equals(convert.tostring(date\_created… ```
[b]#include[/b] <stdio.h> 

[b]void[/b] [b]foo[/b]([b]int[/b] n)
{
   [b]if[/b] ( n >= 0 )
   {
	  [b]printf[/b]("%d ", n);
	  [b]foo[/b](n - 1);
   }
}

[b]void bar[/b]([b]int[/b] n)
{
   [b]if[/b] ( n >= 0 )
   {
	  [b]bar[/b](n - 1);
	  [b]printf[/b]("%d ", n);
   }
}

[b]int main[/b]() 
{
   [b]int[/b] value = 5;
   [b]foo[/b](value); [b]putchar[/b]('\n');
   [b]bar[/b](value); [b]putchar[/b]('\n');
   [b]return[/b] 0; 
}

/* my output
5 4 3 2 1 0 
0 1 2 3 4 5 
*/
``` Your test is redundant, since you are already querying only for matching records. In this case, you will get no rows if there is no match, therefore you will never hit the else clause in the loop.  

  

Instead, it is enough to check if there are any matching records at all. The example below shows how (note that you can put a condition straight into Any() instead of specifying Where()).  

  

C#Copy Code

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace CustomerMaster
{
    public partial class CustomerMaster : System.Web.UI.Page
    {
 
        private void AddData()
        {
            
            OperationsDataContext AddDb = new OperationsDataContext();
            CustomerMast cm = new CustomerMast();
            
                        
            cm.CustomerCode = txtCustCde.Text;
            cm.CustomerName = txtCustName.Text;
            cm.CustomerAddress = txtCustAdd.Text;
            cm.BrkrCode = txtBrkCode.Text;
            cm.BrokerName = txtBrkName.Text.
            cm.CrrCode = txtCrrCode.CarrierCode;
            cm.CarrierName =  txtCrrName.Text;
            cm.StnCode=sm.StationCode;
            cm.StationName = txtStnName.Text;
            cm.VatNo=txtVatNo.Text;
            cm.TinNo=txtTinNo.Text;
            cm.TMCO=txtTMCONo.Text;
            cm.PanNo = txtPAN.Text;
			
	    if(AddDb.CustomerMasts.Any(c=>c.CustomerCode == txtCustCde.Text))
            {
	        Response.Write("Error! CustomerCode Exits");
	    }
	    else
	    {
                AddDb.BrokerMasts.InsertOnSubmit(bm);
                AddDb.CarrierMasts.InsertOnSubmit(crm);
                AddDb.StationMasts.InsertOnSubmit(sm);
                AddDb.CustomerMasts.InsertOnSubmit(cm);

	        AddDb.SubmitChanges();
            }         
        }
 
        protected void btnAdd\_Click(object sender, EventArgs e)
        {
            AddData();
        }
    }
}
``` Try this and see if it works..... But the problem is some libraries does not support  

(#include "XYLock.h")



```
#include <stdio.h>
#include  <iostream>
#include "XYLock.h"

XYCriticalSection myCriticalSection;

void ThreadProc(void *dummy)
{
    while(true)
    {
        try
        {
            XYLock myLock(&myCriticalSection);
            printf("Thread '%X' has the lock\n",::GetCurrentThreadId());
            throw "a test";
        }
        catch(char* p)
        {
            printf("Caught: %s\n",p);
        }
        ::Sleep(1000);
    }
}

void main()
{
    for(int i=0;i<100;i++)
    {
        if(_beginthread(ThreadProc,0,NULL)1)
        {
            printf("Failed to create a thread\n");
            return;
        }
    }

    while(true)
    {
        try
        {
            XYLock myLock(&myCriticalSection);
            printf("The main thread '%X' has the lock\n",::GetCurrentThreadId());
            throw "a test from the main thread";
        }
        catch(char* p) 
        {
            printf("Caught: %s\n",p); 
        } 
        ::Sleep(1000); 
    } 
}
``` as long as you write down the hierarchy manually, there’s certainly the possibility to simplify such transitive from implementations with a macro. [i’ve written one here, feel free to take a look.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=337cce675aa28e99ac030ca783c1c155) going even further one could try to use procedural macros with global state that uses annotations on the… yes, you can using a module.

you might have seen examples of module where a only a symbol is given, e.g. from the docs:

data = mx.sym.variable('data')

fc1 = mx.sym.fullyconnected(data, name='fc1', num\_hidden=128)

act1 = mx.sym.activation(fc1, name='relu1', act\_type="relu")

fc2 = mx.sym.fullyconn… JavaScript *itself* has nothing built in for handling query string parameters. 


Code running in a (modern) browser you can use the [`URL` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) (which is part of the APIs provided by browsers to JS):





```
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
```









For older browsers (including Internet Explorer), you can use [this polyfill](https://github.com/ungap/url-search-params) or the code from the original version of this answer that predates `URL`:


You could access `location.search`, which would give you from the `?` character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.


Then you can parse it with this:





```
function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key]  "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key]  "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
```




You can get the query string from the URL of the current page with:



```
var query = window.location.search.substring(1);
var qs = parse_query_string(query);

``` Resolved:  

  

FORM 1.  

  

Copy Code

```
private void btnModificaContractul\_Click(object sender, EventArgs e)
        {


            string[] IDProdusContractPrelugit = new string[dataProduseContract.Rows.Count];
            string[] IDProdusContractRetras = new string[dataProduseContract.Rows.Count];

            for (int i = 0; i < dataProduseContract.Rows.Count; i++)
            {

                if (Convert.ToBoolean(dataProduseContract.Rows[i].Cells[0].Value) == false)
                {
                    IDProdusContractPrelugit[i] = dataProduseContract.Rows[i].Cells[5].Value.ToString();
                }
                else
                {
                    IDProdusContractRetras[i] = dataProduseContract.Rows[i].Cells[5].Value.ToString();
                }
            }

           

            try
            {
                frmModificaContract ModificareContract = new frmModificaContract(IDProdusContractPrelugit, IDProdusContractRetras);
                ModificareContract.ShowDialog();
            }
            catch { MessageBox.Show("Trebuie să selectaţi un contract din listă pentru a edita.", "Datele furnizate sunt incomplete."); }
           
        }
```
  

  

FORM 2.  

  

Copy Code

```
string[] IDProdusContractPrelugit;
        string[] IDProdusContractRetras;

        public frmModificaContract(string[] IDProdusContractPrelugit, string[] IDProdusContractRetras)
        {
            InitializeComponent();
            this.IDProdusContractPrelugit = IDProdusContractPrelugit;
            this.IDProdusContractRetras = IDProdusContractRetras;
            AfisareProduseContract();
        }


        void AfisareProduseContract()
        {

            foreach (string ContractPrelungit in IDProdusContractPrelugit)
            {
                if (ContractPrelungit != null)
                {
                    Program.Connection.CommandText = "select * from ContractItems WHERE ContractItemId=@ContractItemId";
                    Program.Connection.AddParameter("@ContractItemId", ContractPrelungit);

                    DataTable Table = new DataTable();
                    Program.Connection.FillDataTable(Table, true);


                    for (int i = 0; i < Table.Rows.Count; i++)
                    {
                        if (String.IsNullOrWhiteSpace(Table.Rows[i]["DeletedId"].ToString()))
                        {
                            bool validare;
                            validare = true;

                            dataProduseContract.Rows.Add(validare, Table.Rows[i]["Name"].ToString(), Table.Rows[i]["Quantity"].ToString() + " " + Table.Rows[i]["QuantityUnit"].ToString(), Table.Rows[i]["Payment"].ToString(), Table.Rows[i]["Description"].ToString(), Table.Rows[i]["ContractItemId"].ToString());
                        }
                        else
                        {
                            bool validarescos;
                            validarescos = false;
                            dataProduseContract.Rows.Add(validarescos, Table.Rows[i]["Name"].ToString(), Table.Rows[i]["Quantity"].ToString() + " " + Table.Rows[i]["QuantityUnit"].ToString(), Table.Rows[i]["Payment"].ToString(), Table.Rows[i]["Description"].ToString(), Table.Rows[i]["ContractItemId"].ToString());
                            dataProduseContract.Enabled = false;
                        }

                    }
                }
            }

            
        }
```
  

  

The problem is allwais i have Null value in array. more information: [c++ friend functions](http://www.tutorialspoint.com/cplusplus/cpp_friend_functions.htm)