可能的重复项:
如何将 where 语句发送到在 LINQ 语句中动态执行的方法?
我一直在单独的方法中编写简单的 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;
}
只需要一个类型为 Func<T1, T2, bool>
的参数,其中 T1
和 T2
分别是 Names
和 Places
中的项目类型。
private IEnumerable<NamePlace> GetSomeDataHelper(Func<Name, Place, bool> filter)
{
var query = from name in Names
from place in Places
where filter(name, place)
select new NamePlace {
field1 = name.name,
field2 = place.name,
};
return query;
}
public IEnumerable<NamePlace> GetSomeData1(int num1, int num2)
{
return GetSomeDataHelper((name, place) => name.id == num1 && place.id = num2);
}
将Func<Name, Place,bool>
传递给该方法,在 Where 子句中对其进行计算。
public IEnumerable<NamePlace> GetSomeData(Func<Name,Place, bool> condition)
{
var temp = from Name in Names
from Place in Places
where condition(Name,Place)
select new NamePlace {
field1 = Name.name;
field2 = Place.name;
};
return temp;
}
然后像这样调用函数:
GetSomeData((name,place)=>name.FavNumber=5 && Place.Neighbor==7);
让它让GetSomeData()接受一个谓词:
public IEnumerable<NamePlace> GetSomeData(int num1, int num2, Func<Name, Place, bool> predicate)
{
var temp = from Name in Names
from Place in Places
where predicate(Name, Place)
select new NamePlace {
field1 = Name.name;
field2 = Place.name;
};
return temp;
}
然后你可以这样称呼它:
var results = GetSomeData(num1, num2, (name, place) => name.id == num1 && place.id = num2);