Convert dictionary to list collection in C#

前端 未结 6 1358
余生分开走
余生分开走 2021-01-30 09:54

I have a problem when trying to convert a dictionary to list.

Example if I have a dictionary with template string as key and string as value. Then I wish to convert the

相关标签:
6条回答
  • 2021-01-30 10:19

    If you want to pass the Dictionary keys collection into one method argument.

    List<string> lstKeys = Dict.Keys;
    Methodname(lstKeys);
    -------------------
    void MethodName(List<String> lstkeys)
    {
        `enter code here`
        //Do ur task
    }
    
    0 讨论(0)
  • 2021-01-30 10:32

    If you want to use Linq then you can use the following snippet:

    var listNumber = dicNumber.Keys.ToList();
    
    0 讨论(0)
  • 2021-01-30 10:38

    If you want convert Keys:

    List<string> listNumber = dicNumber.Keys.ToList();
    

    else if you want convert Values:

    List<string> listNumber = dicNumber.Values.ToList();
    
    0 讨论(0)
  • 2021-01-30 10:40
    foreach (var item in dicNumber)
    {
        listnumber.Add(item.Key);
    }
    
    0 讨论(0)
  • 2021-01-30 10:43

    To convert the Keys to a List of their own:

    listNumber = dicNumber.Select(kvp => kvp.Key).ToList();
    

    Or you can shorten it up and not even bother using select:

    listNumber = dicNumber.Keys.ToList();
    
    0 讨论(0)
  • 2021-01-30 10:43

    Alternatively:

    var keys = new List<string>(dicNumber.Keys);
    
    0 讨论(0)
提交回复
热议问题