如果适用,将嵌套的ForEach替换为Select

时间:2009-08-25 22:17:27

标签: c# .net linq extension-methods ienumerable

是否可以用ForEach()或其他方法替换方法Select()用法,用嵌套扩展方法在一个字符串中编写下一个代码?或者可能有其他方法来改进算法?

var list = new List<IStatementParser>();

System.IO.Directory.GetFiles(path, "*.dll")
    .ForEach(f => System.Reflection.Assembly.LoadFrom(f)
        .GetTypes()
        .Where(t => !t.IsInterface && typeof(IFoo).IsAssignableFrom(t))
        .ForEach(t => list.Add((IFoo)Activator.CreateInstance(t))));

return list.ToDictionary(k => k.Name, v => v.GetType());

它加载path中实现IFoo的程序集中的所有类,并将它们添加到Dictionary<string, Type>,其中string为IFoo.Name

2 个答案:

答案 0 :(得分:3)

我认为这里根本不需要中间人List - 你可以这样做:

return (from dll in Directory.GetFiles(path, "*.dll")
        let asm = Assembly.LoadFrom(dll)
        from t in asm.GetTypes()
        where !t.IsInterface && typeof(IFoo).IsAssignableFrom(t)
        select (IFoo)Activator.CreateInstance(t)
       ).ToDictionary(foo => foo.Name, foo => foo.GetType())

顺便说一句,您可能还想在尝试实例化之前检查类型是否为abstract

答案 1 :(得分:3)

var foos =
    from dllFile in Directory.GetFiles(path, "*.dll")
    from type in Assembly.LoadFrom(dllFile).GetTypes()
    where !type.IsInterface && typeof(IFoo).IsAssignableFrom(type)
    select (IFoo) Activator.CreateInstance(type);

return foos.ToDictionary(foo => foo.Name, foo => foo.GetType());