如何从字典关键字查询中获取扁平列表,其中值是列表

本文关键字:列表 获取 字典 关键字 查询 | 更新日期: 2023-09-27 17:59:04

我正在尝试创建一个事件/消息系统,订阅者可以在其中订阅常规事件类型或特定事件类型。

我有一个事件类型的字典,其中包含所述类型的订阅者的列表,为了向订阅者通知事件,我想获得这些列表中所有订阅的扁平列表,其中订阅的类型等于事件的类型或可从事件的类型分配;换句话说,当dictionary关键字满足这个条件时。

如何获得从字典键查询的列表项的扁平列表(使用linq)?


我的在制品代码:

private Dictionary<Type, List<SomeEventDelegate>> subscriptions;
// ...other code...
public void Dispatch(SomeEvent someEvent)
    {
        // This should get the Key-Value pairs... How do I get a flattened list of all items in the values (which are lists themselves)?
        List<SomeEventDelegate> subscribers =
            from subscription in subscriptions
            where subscription.Key.IsAssignableFrom(someEvent.GetType())
            select subscription;
        //After I have the flattened list, I will dispatch the event to each subscriber here, in a foreach loop.
    }

如何从字典关键字查询中获取扁平列表,其中值是列表

SelectMany应该完成以下工作:

List<SomeEventDelegate> subscribers =
    subscriptions.Where(kvp => 
        kvp.Key.IsAssignableFrom(someEvent.GetType())
    ).SelectMany(kvp => kvp.Value)
    .ToList();

您只能使用链式方法调用语法来完成此操作。您向它传递一个lambda,该lambda从参数中选择一个IEnumerable<T>,然后它将从查询中的每个项收集的所有可枚举对象合并为一个大的平面查询,并返回该查询。

如果您喜欢查询语法(因此不必担心使用的确切方法),为什么不继续查询:

   List<SomeEventDelegate> subscribers =
        (from subscription in subscriptions
         where subscription.Key.IsAssignableFrom(someEvent.GetType())
         from subscriber in subscription.Value
         select subscriber)
        .ToList();