Possible Duplicate:
How can I send where statements to a method which are dynamically executed in a LINQ statement?
I have been writing simple LINQ queries in separate methods, but they have become repetitive. Please excuse the silly example of name and place, the only part that changes in all three methods is the ‘where’ clause.
How can this repetitive code be made more dry?
For example, something like a helper method that takes everything the same but allows change in where clause.
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;
}
All you need is a parameter of type
Func<T1, T2, bool>whereT1andT2are the types of the items inNamesandPlacesrespectively.