2

可能重复:
如何将 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;
}
4

3 回答 3

4

您所需要的只是一个类型参数Func<T1, T2, bool>whereT1和分别是 in和T2中的项目的类型。NamesPlaces

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);
}
于 2013-01-30T18:18:25.687 回答
0

将 a 传递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);
于 2013-01-30T18:17:00.077 回答
0

你可以让它 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);
于 2013-01-30T18:17:13.057 回答