我一直在用不同的方法编写简单的 LINQ 查询,但它们变得重复了。请原谅名称和地点的愚蠢示例,所有三种方法中唯一变化的部分是“where”子句。
怎样才能使这种重复的代码更枯燥?
例如,类似于辅助方法的东西,它采用相同的方式,但允许在 where 子句中进行更改。
public IEnumerable<NamePlace> GetSomeData(int num1, int num2)
{
var temp = from Name in Names
from Place in Places
where Name.id == num1 && Place.id = num2
select new NamePlace {
field1 = Name.name;
field2 = Place.name;
};
return temp;
}
public IEnumerable<NamePlace> GetSomeData2(int num1, int num2)
{
var temp = from Name in Names
from Place in Places
where Name.age == num1 && Place.streetNumber = num2
select new NamePlace {
field1 = Name.name;
field2 = Place.name;
};
return temp;
}
public IEnumerable<NamePlace> GetSomeData3(int num1, int num2)
{
var temp = from Name in Names
from Place in Places
where Name.favouriteNumber == num1 && Place.neighbourNumber = num2
select new NamePlace {
field1 = Name.name;
field2 = Place.name;
};
return temp;
}