Home > DeveloperSection > Forums > Using Key Value Pair with lists to dynamically create a paired value array
Ashish Pandey

Total Post:128

Posted on    August-14-2014 5:02 AM

 C# C# 

 1 Reply(s)
 1195  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?

Pravesh Singh

Total Post:412

Posted on    August-14-2014 5:24 AM

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));

Don't want to miss updates? Please click the below button!

Follow MindStick