Paul
Paul

Reputation: 594

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?

Upvotes: 1

Views: 329

Answers (1)

VipinKV
VipinKV

Reputation: 66

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)];
    }

Upvotes: 1

Related Questions