c# predefine LINQ select
本文关键字:select LINQ predefine | 更新日期: 2023-09-27 18:03:38
我想将相同的SELECT
应用于queries
的数量,我该如何做到这一点?我想做一些模板,我猜?
var query = (from b in db.routes select new
{ name = b.name,
age = b.age});
我想预先定义name= b.k ame和age = b.g age.
谢谢
您可以创建带有IEnumerable<SomeBaseClassOrInterfacee>
参数的方法。然后你可以在方法中对给定的参数执行select。
public class Generic
{
protected Generic(string name, int age)
{
Name = name;
Age = age;
}
public string Name { get; private set; }
public int Age { get; private set; }
}
public class Human : Generic
{
public Human(string name, string surname, int age) : base(name, age)
{
Surname = surname;
}
public string Surname { get; private set; }
}
public class Pet : Generic
{
public Pet(string name, int registrationCode, int age)
: base(name, age)
{
RegistrationCode = registrationCode;
}
public int RegistrationCode { get; private set; }
}
static void Main(string[] args)
{
IEnumerable<Pet> pets = new List<Pet>();
IEnumerable<Human> palls = new List<Human>();
var resPets = SelectAgeGreaterThen10<Pet>(from p in pets where p.Name.StartsWith("A") select p);
var resHumans = SelectAgeGreaterThen10<Human>(from p in palls where p.Name.StartsWith("B") select p);
}
private static IEnumerable<T> SelectAgeGreaterThen10<T>(IEnumerable<Generic> source) where T : Generic
{
return from s in source where s.Age > 10 select (T)s;
}
您的示例的棘手之处在于您使用的是匿名类型-这意味着您不能编写方法(您不能声明返回类型),并且您不能将lambda表达式分配给局部变量(您需要能够指定将lambda表达式转换为的类型)。
您也不能仅仅使用类型推断从泛型方法返回一些东西——因为您不能仅仅指定输入类型。但是,您可以对泛型类使用类型推断:
public static class Functions<T>
{
public static Func<T, TResult> Create<TResult>(Func<T, TResult> func)
{
return func;
}
}
那么你可以写:
var projection = Functions<Route>.Create(r => new { r.name, r.age });
var query = db.routes
.Select(projection)
...;
但是如果您真的想在多个地方使用相同的投影,您应该考虑创建一个命名的结果类型——此时您可以使用任何其他选项,包括转换方法。
这个看起来怎么样:
class NameAndAge
{
public String Name;
public Int32 Age;
}
class Whatever
{
public IEnumerable<NameAndAge> GetNameAndAges(IEnumerable<dynamic> enumerable)
{
return from b in enumerable select new NameAndAge { Name = b.name,
Age = b.age};
}
}
您可能需要将参数类型中的dynamic
替换为db.routes
中元素的类型。