Daryl Gill
Daryl Gill

Reputation: 5524

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

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?

Upvotes: 1

Views: 3427

Answers (2)

CodeCaster
CodeCaster

Reputation: 151588

You cannot nest code in a collection initializer like that. If you remember a collection initializer basically calls Add() on the parent for each element it contains, you understand why that isn't possible.

Either format the code so it calls list.Add(new KVP...) in the foreach:

var list = new List<KeyValuePair<string, string>>();

foreach (string Elements in Results)
{
    list.Add(new KeyValuePair<string,string>(DBConfigElements[Count], Elements));
    Count++;
}

Or use Linq:

var list = Results.Select((element, index) => 
    new KeyValuePair<string,string>(DBConfigElements[index], element))
                   .ToList()

You also might want to use somewhat more meaningful variable names than "list" and "result".

Upvotes: 5

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

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

Upvotes: 1

Related Questions