C# ToDictionary lambda select index and element?

前端 未结 3 1022
野的像风
野的像风 2021-01-01 12:57

I have a string like string strn = \"abcdefghjiklmnopqrstuvwxyz\" and want a dictionary like:

Dictionary(){
    {\'a\',0},
    {         


        
相关标签:
3条回答
  • 2021-01-01 13:19

    Use the .Select operator first:

    strn
        .Select((x, i) => new { Item = x, Index = i })
        .ToDictionary(x => x.Item, x => x.Index);
    
    0 讨论(0)
  • 2021-01-01 13:34

    You could try something like this:

        string strn = "abcdefghjiklmnopqrstuvwxyz";
    
    Dictionary<char,int> lookup = strn.ToCharArray()
        .Select( ( c, i ) => new KeyValuePair<char,int>( c, i ) )
            .ToDictionary( e => e.Key, e => e.Value );
    
    0 讨论(0)
  • 2021-01-01 13:38

    What am I doing wrong?

    You're assuming there is such an overload. Look at Enumerable.ToDictionary - there's no overload which provides the index. You can fake it though via a call to Select:

    var dictionary = text.Select((value, index) => new { value, index })
                         .ToDictionary(pair => pair.value,
                                       pair => pair.index);
    
    0 讨论(0)
提交回复
热议问题