gpt4 book ai didi

c# - 合并两个 LINQ 查询?

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:09 24 4
gpt4 key购买 nike

我想我有精神障碍,但有人可以告诉我如何将这两个 LINQ 语句合并为一个吗?

/// <summary>
/// Returns an array of Types that implement the supplied generic interface in the
/// current AppDomain.
/// </summary>
/// <param name="interfaceType">Type of generic interface implemented</param>
/// <param name="includeAbstractTypes">Include Abstract class types in the search</param>
/// <param name="includeInterfaceTypes">Include Interface class types in the search</param>
/// <returns>Array of Types that implement the supplied generic interface</returns>
/// <remarks>
/// History.<br/>
/// 10/12/2008 davide Method creation.<br/>
/// </remarks>
public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool includeAbstractTypes, bool includeInterfaceTypes)
{
// Use linq to find types that implement the supplied interface.
var allTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(p => p.IsAbstract == includeAbstractTypes
&& p.IsInterface == includeInterfaceTypes);

var implementingTypes = from type in allTypes
from intf in type.GetInterfaces().ToList()
where intf.FullName != null && intf.FullName.Contains(interfaceType.FullName)
select type;

return implementingTypes.ToArray<Type>();
}

我正在避免使用 IsAssignableFrom,因为它在不提供特定类型的通用接口(interface)时似乎会失败,因此我相信在 IsAssignableFrom 上使用 FullName caparison 应该就足够了,例如:

namespace Davide
{
interface IOutput<TOutputType> { }

class StringOutput : IOutput<string> { }
}

typeof(IOutput<>).FullName 将返回“Davide+IOutput`1”

typeof(StringOutput).GetInterfaces()[0].FullName 将返回“Davide+IOutput`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”

因此使用 FullName.Contains 就足够了

最佳答案

SelectMany 转换为第二个“来自”:

var implementors = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsAbstract == includeAbstractTypes
where type.IsInterface == includeInterfaceTypes
from intf in type.GetInterfaces()
where intf.FullName != null &&
intf.FullName.Contains(interfaceType.FullName)
select type;

为了主观清晰,我将条件分成多个“where”子句,顺便说一下。

这可以编译,但我还没有测试它是否真的有效 :) 正如另一个答案所示,您可以将“Any”与 GetInterfaces() 一起使用,而不是最后的“from”子句。

请注意,无需到处调用 ToList() - LINQ 旨在能够处理整个序列。

顺便说一句,我不确定您为什么要通过 type.GetInterfaces() 进行检查。与使用 Type.IsAssignableFrom 相比,有什么不同(和可取的)吗? ?这将使它更简单:

var implementors = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsAbstract == includeAbstractTypes
where type.IsInterface == includeInterfaceTypes
where interfaceType.IsAssignableFrom(type)
select type;

您实际上在某个地方的不同程序集中有相同的接口(interface)类型名称吗?

关于c# - 合并两个 LINQ 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/355875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com