几个常用的LINQ查询
用来备份,以后更新并查阅。:)
#region GetFiles
/// <summary>
/// 获得指定路径下的所有文件
/// </summary>
/// <param name="path">有效路经</param>
/// <returns></returns>
public IEnumerable<FileInfo> GetFiles(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
if (directory == null)
return null;
return
from f in directory.GetFiles()
select f;
}
/// <summary>
/// 测试GetFiles
/// </summary>
[TestMethod]
public void TestGetFiles()
{
string path = Environment.SystemDirectory;
var result = GetFiles(path);
Assert.IsNotNull(result);
foreach (var item in result)
{
Assert.IsInstanceOfType(item, typeof(FileInfo));
Assert.IsTrue(File.Exists(item.FullName));
}
}
#endregion
#region GetReturnSpecifiedInterfacedMethods
/// <summary>
/// 获得指定Assembly中返回指定接口类型名称的方法信息
/// </summary>
/// <param name="assembly">Assembly</param>
/// <param name="interfaceType">接口类型名称</param>
/// <returns></returns>
public IEnumerable<MethodInfo> GetReturnSpecifiedInterfacedMethods(Assembly assembly, string interfaceTypeName)
{
if (assembly == null) throw new ArgumentNullException("assembly");
if(string.IsNullOrEmpty(interfaceTypeName)) throw new ArgumentNullException("interfaceTypeName");
return
from type in assembly.GetTypes()
from method in type.GetMethods()
where
method.ReturnType.GetInterface(interfaceTypeName) != null
select method;
}
/// <summary>
/// 测试GetReturnSpecifiedInterfacedMethods
/// </summary>
[TestMethod]
public void TestGetReturnSpecifiedInterfacedMethods()
{
string typeName = "IEnumerable`1";
Assembly assembly = AppDomain.CurrentDomain.GetAssemblies()[0];
var result = GetReturnSpecifiedInterfacedMethods(assembly, typeName);
Assert.IsNotNull(result);
foreach (var item in result)
{
Assert.IsInstanceOfType(item, typeof(MethodInfo));
Assert.IsNotNull(item.ReturnType.GetInterface(typeName));
}
}
#endregion
#region GetAssemblyStaticMethods
/// <summary>
/// 获得指定Assembly包含的静态方法信息
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
public IEnumerable<MethodInfo> GetAssemblyStaticMethods(Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException("assembly");
return
from type in assembly.GetTypes()
from method in type.GetMethods()
where
method.IsStatic
select method;
}
/// <summary>
/// 测试GetAssemblyStaticMethods
/// </summary>
[TestMethod]
public void TestGetAssemblyStaticMethods()
{
Assembly assembly = AppDomain.CurrentDomain.GetAssemblies()[0];
var result = GetAssemblyStaticMethods(assembly);
Assert.IsNotNull(result);
foreach (var item in result)
{
Assert.IsInstanceOfType(item, typeof(MethodInfo));
Assert.IsTrue(item.IsStatic);
}
}
浙公网安备 33010602011771号