Matias Cicero
Matias Cicero

Reputation: 26321

List to Dictionary with incremental keys in one line LINQ statement

I have this list:

var items = new List<string>() { "Hello", "I am a value", "Bye" };

I want it to convert it to a dictionary with the following structure:

var dic = new Dictionary<int, string>()
{
     { 1, "Hello" },
     { 2, "I am a value" },
     { 3, "Bye" }
};

As you can see, the dictionary keys are just incremental values, but they should also reflect the positions of each element in the list.

I am looking for a one-line LINQ statement. Something like this:

var dic = items.ToDictionary(i => **Specify incremental key or get element index**, i => i);

Upvotes: 8

Views: 2894

Answers (3)

CathalMF
CathalMF

Reputation: 10055

static void Main(string[] args)
{
    var items = new List<string>() { "Hello", "I am a value", "Bye" };
    int i = 1;
    var dict = items.ToDictionary(A => i++, A => A);

    foreach (var v in dict)
    {
        Console.WriteLine(v.Key + "   " + v.Value);
    }

    Console.ReadLine();    
}

Output

1   Hello
2   I am a value
3   Bye

EDIT: Out of curosity i did a performance test with a list of 3 million strings.

1st Place: Simple For loop to add items to a dictionary using the loop count as the key value. (Time: 00:00:00.2494029)

2nd Place: This answer using a integer variable outside of LINQ. Time(00:00:00.2931745)

3rd Place: Yuval Itzchakov's Answer doing it all on a single line. Time (00:00:00.7308006)

Upvotes: 3

Reza Bayat
Reza Bayat

Reputation: 413

var items = new List<string>() { "Hello", "I am a value", "Bye" };

solution #1:

var dic2 = items.Select((item, index) => new { index, item })
                .ToDictionary(x => x.item, x => x.index);

solution #2:

int counter = 0;
var dic = items.ToDictionary(x => x, z => counter++);

Upvotes: -1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

You can do that by using the overload of Enumerable.Select which passes the index of the element:

var dic = items.Select((val, index) => new { Index = index, Value = val})
               .ToDictionary(i => i.Index, i => i.Value);

Upvotes: 21

Related Questions