LeMoussel
LeMoussel

Reputation: 5767

How to select values and key in a Dictionary of lists?

I have this data :

public class MetaLink
{
    public long LinkNumbering { get; set; }
    public long TargetPageId { get; set; }
    public string TargetUrl { get; set; }
    public LinkType LinkOfType { get; set; }
}
public static ConcurrentDictionary<int, List<MetaLink>> Links = new ConcurrentDictionary<int, List<MetaLink>>();

How can I obtain all index of MetaLink object in the list dictionnary values and the correspondig dictionnary key with TargetUrl property == "Some value"

Perhaps is possible with Linq, but I don't find it. I do this :

var someLinks = Links.Values.Where(kvp => kvp.Any(ml => ml.TargetUrl == "Some value"));

But I can't get the correspondig dictionnary int key

Upvotes: 0

Views: 2758

Answers (2)

D Stanley
D Stanley

Reputation: 152511

You're close - you want

var someLinks = Links.Where(kvp => kvp.Value.Any(ml => ml.TargetUrl == "Some value")) 
                           // all key.value pairs where the Value contains the target URL
                     .Select(kvp => kvp.Key);   //keys for those values

Upvotes: 1

HashCoder
HashCoder

Reputation: 946

Give a try on this. Haven't compiled.

var key = Links.Where(kvp => kvp.Value.Any(ml => ml.TargetUrl == "Some value")).Select(x => x.Key).SingleOrDefault();

Upvotes: 0

Related Questions