I have a class that defines a list and two looping functions that find the items in the list that have some property. Can these two looping functions be combined into one more generic looping function that has the inner Bar.Function() as a parameter?
class Foo {
List<Bar> bar;
List<int> SomeFunc() {
List<int> list;
for (i...) {
if (bar[i].IsSomething()) {
list.Add(i);
}
}
return list;
}
List<int> SomeOtherFunc() {
List<int> list;
for (i...) {
if (bar[i].IsSomethingElse()) {
list.Add(i);
}
}
return list;
}
}
Yes, this is easy if you use lambdas:
As others have mentioned, in this particular case, there’s already a relatively succinct construct in place for the filtering you’re doing (improved with phoog’s suggestion):
And you can also combine both of these solutions to get some very clean code: