Search code examples
c#listlinqdictionarykeyvaluepair

convert List<T> to Dictionary<string,T> with Key set to a property of T


public class Quote
{
    public decimal Price { get; set; }
    public string Symbol { get; set; }
}

public List<Quote> quotes = 
    new List<Quote>(){new Quote{Price=100.00,Symbol="AAPL"},
                      new Quote{Price=200.00,Symbol="GOOG"}}

List<string,Quote> positions = new List<string,Quote>();

I want to set each position.Key to Quote.Symbol and each position.Value to Quote

What's the best way to convert ?


Solution

  • If i understand what you are asking (and that's a big if), it should be as simple as

    var someDictionary = quotes.ToDictionary(x => x.Symbol);
    

    Enumerable.ToDictionary Method

    Creates a Dictionary from an IEnumerable.

    Also take a look at

    Enumerable.ToLookup Method

    Creates a generic Lookup from an IEnumerable.

    A dictionary is a 1:1 map (each key is mapped to a single value), and a dictionary is mutable (editable) after the fact.

    A lookup is a 1:many map (multi-map; each key is mapped to an IEnumerable<> of the values with that key), and there is no mutate on the ILookup<,> interface.