Domanda

I have one Dictionary declared as type

var dictionary1 = Dictionary<string, Type1>

and another as

var dictionary2 = Dictionary<string, Type2>

Each dictionary value type has a public variable called classid so:

dictionary1["key"].classid = 100

is also in:

dictionary2["key"].classid = 100

I know they are of different types, but is there an inbuilt way to find the intersections of just these two private variables and possibly return me a dictionary of that single type? So if the classid were equivalent I could get an intersected dictionary of Type Dictionary1?

È stato utile?

Soluzione

This isn't the most elegant query, but it should do the trick:

var intersection = dictionary1
.Where(kvp1 => 
   dictionary2.ContainsKey(kvp1.Key) 
   && dictionary2[kvp1.Key].classid = kvp1.Value.classid)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

This should fetch all key-value pairs in dictionary1 whose keys also exist in dictionary2, and whose classid matches the dictionary2 object's classid. Those key-value pairs are then transformed into a new dictionary.

Altri suggerimenti

As an alternative to Where/ContainsKey, you could also use a simple join, which is more readable and (probably) faster for larger sets of data:

var result = from kv1 in dictionary1
             join kv2 in dictionary2 on 
                new {kv1.Key, kv1.Value.classid} equals 
                new {kv2.Key, kv2.Value.classid}
             select kv1;

var new_dict = result.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

you can use below mentioned code

        Dictionary<int, string> t = new Dictionary<int, string>();
        Dictionary<int, string> t1 = new Dictionary<int, string>();
        t.Add(100, "f");
        t1.Add(100, "f2");

        var abc=t.Where(p=>t1.Any(q=>q.Key==p.Key));

Yes but dictionaries may not be what you want and this question may be a duplicate phrased differently:

C# Linq intersect/except with one part of object

BTW the property you want to use for the intersection should be public.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top