减少类似查询中的重复

时间:2013-01-30 18:09:58

标签: c# linq

  

可能重复:
  How can I send where statements to a method which are dynamically executed in a LINQ statement?

我一直在用不同的方法编写简单的LINQ查询,但它们已经变得重复了。请原谅名称和地点的愚蠢示例,所有三种方法中唯一改变的部分是'where'子句。

如何使这个重复的代码更加dry

例如,类似于辅助方法的方法,它将所有内容都相同但允许更改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;
}

3 个答案:

答案 0 :(得分:4)

您需要的只是Func<T1, T2, bool>类型的参数,其中T1T2分别是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);
}

答案 1 :(得分:0)

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);

答案 2 :(得分: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);