Paul Paul - 11 days ago 7
Java Question

How to get value from Map by one field of key?

I have a map:

public class MyKey {
...
private long id;
...
}

Map<MyKey, String> myMap;


How to get value from
myMap
by
MyKey.id
field?

Answer

Please find the reply in C#. I think we can achieve the same using a Linq expression. Please find the sample code below hope it will help.

    public class MyKey
    {
        public long ID { get; set; }
    }

    static void Main(string[] args)
    {
        Dictionary<MyKey, String> myMap = new Dictionary<MyKey, string>();
        myMap.Add(new MyKey() { ID = 100 }, "One");
        myMap.Add(new MyKey() { ID = 200 }, "Two");
        myMap.Add(new MyKey() { ID = 300 }, "Three");

        long searchKey = 200;
        string value = myMap[myMap.Keys.FirstOrDefault(x => x.ID == searchKey)];
    }