USING KEY VALUE PAIR WITH LISTS TO DYNAMICALLY CREATE A PAIRED VALUE ARRAY

Ashish Pandey

Total Post:128

Points:898
Posted by  Ashish Pandey
C# 
C#
 1219  View(s)
Ratings:
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);

                    Count++;

                } // 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. Pravesh Singh

    Post:412

    Points:2888
    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));

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!