Here we are talking about filtering list items again :). I got two comment suggesting the use of yield return.
James Curran said:
Don’t build a new list if you don’t have to.
private static IEnumerable EvenSlicker_FilterPositiveItems(IEnumerable t)
{foreach(int n in t)
if (n > 0)
yield return n;
}
The advantage is if you try using the method this this:
foreach(int n in FilterPositiveItems(myList) {…}
Your way is O(2N) while mine is O(N)
Hi all
I was into filtering items lately
and I have decided to write about some of the techniques out there starting with the old
Well we have all used this before once you get a list in your hands just iterate through all the items and select the ones you want:
1: private static List<int> TheOld_FilterPositiveItems(List<int> t)
2: {
3: List<int> ret = new List<int>();
4: foreach (int i in t)
5: {
6: if (i > 0)
7: {
8: ret.Add(i);
9: }
10: }
11: return ret;
12: }
I hope you are not using this method. As there are other good methods like this one:
Hi
A while back I wrote an article about How to sort data by manipulating the view only, This article will handle filtering the data without changing it.
I had a large collection that I needed to display and allow the user to filter it using many parameters. After searching for a while I found a very elegant solution:
what are predicates? I will Quote
Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
You can read more about it here.
A predicate Is a template so you will have to specify the type for instance:
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More