How to put all types that implement a specific common interface in a dictionary?

Given a specific interface ITarget<T>and a specific type myType, this is how you would determine Tif it myTypeimplements ITarget<T>. (This code snippet is taken from an answer to an earlier question .)

foreach (var i in myType.GetInterfaces ())
    if (i.IsGenericType
        && i.GetGenericTypeDefinition() == typeof(ITarget<>))
        return i.GetGenericArguments ()[0] ;

However, this check is only one type myType. How can I create a dictionary of all such type parameters, where is the key Tand the value myType? I think it will look something like this:

var searchTarget = typeof(ITarget<>);
var dict = Assembly.GetExecutingAssembly().[???]
             .Where(t => t.IsGenericType
                    && t.GetGenericTypeDefinition() == searchTarget)
             .[???];

What happens in spaces?

+3
source share
1 answer
var searchTarget = typeof(ITarget<>);

var dict = Assembly.GetExecutingAssembly()
    .GetTypes()
    .SelectMany(t => t.GetInterfaces()
                      .Where(i => i.IsGenericType
                          && (i.GetGenericTypeDefinition() == searchTarget)
                          && !i.ContainsGenericParameters),
                (t, i) => new { Key = i.GetGenericArguments()[0], Value = t })
    .ToDictionary(x => x.Key, x => x.Value);

, , ITarget<> - , class Foo : ITarget<string> class Bar : ITarget<string> - ToDictionary ArgumentException, , .

" ", .

  • ToLookup ToDictionary Lookup<K,V>:

    var dict = Assembly.GetExecutingAssembly()
        .GetTypes()
        .SelectMany(/* ... */)
        .ToLookup(x => x.Key, x => x.Value);
    
  • - Dictionary<K,List<V>>, :

    var dict = Assembly.GetExecutingAssembly()
        .GetTypes()
        .SelectMany(/* ... */)
        .GroupBy(x => x.Key, x => x.Value)
        .ToDictionary(g => g.Key, g => g.ToList());
    
+6

Source: https://habr.com/ru/post/1746855/


All Articles