c# - 减少类似查询的重复

标签 c# linq

Possible Duplicate:
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;
}

最佳答案

您所需要的只是 Func<T1, T2, bool> 类型的参数哪里T1T2Names 中项目的类型和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);
}

关于c# - 减少类似查询的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610813/

相关文章:

c# - 对已分配的字符串使用未分配的局部变量错误

c# - 如何在C#中设计一个不会失效的DataType

c# - 如何选择与对象列表中的属性值共享属性值的所有对象?

c# - 在 Linq to Entity Framework 查询中按数组值排序

java - LINQ的类似功能

c# - 如何使用 json.net 在 POST 请求上进行 asp.net core 模型绑定(bind)?

c# - .NET 中是否有类似 Apple 的 UIWebView 的类?

c# - ComboBox WPF 数据绑定(bind)到 DataView

LinqToSQl 和 Member 访问在类型异常上不合法

c# - Microsoft 是否修复了 .NET 4.0 中的 Linq to Entities 性能问题?