Select Value of List of KeyValuePair

前端 未结 4 1258
滥情空心
滥情空心 2021-01-03 19:43

How can i select the value from the List of keyvaluepair based on checking the key value

List> myList = new         


        
相关标签:
4条回答
  • 2021-01-03 20:12

    NOTE

    The generic Dictionary class, introduced in .NET 2.0, uses KeyValuePair.

    ITs better you make use of

    Dictionary<TKey, TValue>.ICollection<KeyValuePair<TKey, TValue>>
    

    and use ContainsKey Method to check the the key is there or not ..

    Example :

    ICollection<KeyValuePair<String, String>> openWith =
                new Dictionary<String, String>();
    openWith.Add(new KeyValuePair<String,String>("txt", "notepad.exe"));
    openWith.Add(new KeyValuePair<String,String>("bmp", "paint.exe"));
    openWith.Add(new KeyValuePair<String,String>("dib", "paint.exe"));
    openWith.Add(new KeyValuePair<String,String>("rtf", "wordpad.exe"));
    
    if (!openWith.ContainsKey("txt"))
    {
           Console.WriteLine("Contains Given key");
    }
    

    EDIT

    To get value

    string value = "";
    if (openWith.TryGetValue("tif", out value))
    {
        Console.WriteLine("For key = \"tif\", value = {0}.", value);
        //in you case 
       //var list= dict.Values.ToList<Property>(); 
    }
    

    in your caseu it will be

    var list= dict.Values.ToList<Property>(); 
    
    0 讨论(0)
  • 2021-01-03 20:13

    If you need to use the List anyway I'd use LINQ for this query:

    var matches = from val in myList where val.Key == 5 select val.Value;
    foreach (var match in matches)
    {
        foreach (Property prop in match)
        {
            // do stuff
        }
    }
    

    You may want to check the match for null.

    0 讨论(0)
  • 2021-01-03 20:27

    Use Dictionary<int, List<Properties>>. Then you can do

    List<Properties> list = dict[5];
    

    As in:

    Dictionary<int, List<Properties>> dict = new Dictionary<int, List<Properties>>();
    dict[0] = ...;
    dict[1] = ...;
    dict[5] = ...;
    
    List<Properties> item5 = dict[5]; // This works if dict contains a key 5.
    List<Properties> item6 = null;
    
    // You might want to check whether the key is actually in the dictionary. Otherwise
    // you might get an exception
    if (dict.ContainsKey(6))
        item6 = dict[6];
    
    0 讨论(0)
  • 2021-01-03 20:30

    If you're stuck with the List, you can use

    myList.First(kvp => kvp.Key == 5).Value
    

    Or if you want to use a dictionary (which might suit your needs better than the list as stated in the other answers) you convert your list to a dictionary easily:

    var dictionary = myList.ToDictionary(kvp => kvp.Key);
    var value = dictionary[5].Value;
    
    0 讨论(0)
提交回复
热议问题