2

I have a class A containing an array of key/values pairs described by class B. One of the key is called "name". I want to use Linq to build a Dictionary<string, Dictionary<string, string>> where key of first dictionary is the attribute called "name" in the B array and the value is a second dictionary that contains the key/value pairs of B.

public class A
{
    public int a;
    public B[] b;
}

public class B
{
    public string key;
    public string value;
}

A[] a = new A[]
{
    new A { a = 1, b = new B[] { new B { key = "name", value = "n1"}, new B { key = "test", value = "t1" } }, },
    new A { a = 2, b = new B[] { new B { key = "name", value = "n2"}, new B { key = "test", value = "t2" } }, },
};    

So in fact I would like to build the following dictionary using Linq on array "a":

Dictionary<string, Dictionary<string, string>> d = new Dictionary<string, Dictionary<string, string>>()
{
    { "n1",  new Dictionary<string, string>() { { "name", "n1" }, { "test", "t1" } } },
    { "n2",  new Dictionary<string, string>() { { "name", "n2" }, { "test", "t2" } } },
};

1 Answer 1

2

It should be:

var dict = a.ToDictionary(
    x => x.b[0].value, 
    y => y.b.ToDictionary(z => z.key, z => z.value)
);

The only "fun" part of this LINQ expression is that I had to use up to z parameters (x, y, z)... It took me three compilations to get it right (I always name the parameters x)

Revised for comment:

var dict = a.ToDictionary(
    x => x.b.First(y => y.key == "name").value, 
    y => y.b.ToDictionary(z => z.key, z => z.value)
);
Sign up to request clarification or add additional context in comments.

3 Comments

Cool ! The parameter "name" may be randomly placed in the array (not necessarily the first element). How could I modify the expression to cope with this ?
@user957479 Updated
Thanks, it always looks so easy when you see the result ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.