Advertise with us

Using Key Value Pair with lists to dynamically create a paired value array

Posted by  Ashish Pandey
 1942  View(s)
Rate this:

I'm currently using XDocument to read specific attributes from a XML Document, This works without a hitch. Now, I'm trying to create an array with Keys and Values to be later used for Validation. This may be an isolated incident (due to being unable to google/research the errors) , but the error messages which I am experiencing has totally stumped me, the syntax does look correct. The code follows:

    public Array GetConfig(string FilePath)
            var Document = XDocument.Load("CoreConfig.xml");
            var Results = Document.Descendants().Elements("Database");
            var ReturnList = new List<KeyValuePair<string,string>>();
                string[] DBConfigElements = new string[4]{"Server","Username","Password","Database"};
                int Count = 1;
                var list = new List<KeyValuePair<string, string>>() { // Errors 1,2,3
                foreach (string Elements in Results){
                    new KeyValuePair<string,string>(DBConfigElements[Count],Elements);
                } // Error 4

The error messages Presented are:

Error 1 Invalid initializer member declarator

Error 2 ; expected

Error 3 } expected

Error 4 { expected

I have labeled the code which line the error message is being triggered from. The syntax does look correct, so where is it that I am going wrong?

  1. Re: Using Key Value Pair with lists to dynamically create a paired value array

    Hi Ashish,

    You can't use foreach in an object initializer, but you can use Linq:

    var list = new List<KeyValuePair<string, string>>(
                Results.Select(r => new KeyValuePair<string,string>(DBConfigElements[Count++],r));

      Modified On Apr-04-2018 05:35:44 AM