Hey guys,
I was trying to find some way to filter and sort data in a Generic Collection
of List<> Type but couldn't find any way to do this.
I have Tried to use BindingSource which didn't really filter any of the data in my collection.

Anyone have any idea how I can filter and sort data in a List<> Collection ?

Thanks!

Recommended Answers

All 5 Replies

There is no easy way to filter data with a generic collection unfortunately.

But sorting shouldn't be too hard since generic collections have a Sort function you can call. To implement a custom sorting algorithm check out this link on sorting points. It should help as a general guideline.

hope that helps

Thanks
But what about filtering?
this is my main problem.
what's the best be to filter the List<> ?

It depends on what your doing with that list. Worst case, you can write a for loop that manually displays only the elements that aren't currently filtered out. Otherwise the only way I know off the top of my head is the Filter function in BindingSource, but that's more for DataSets...

Personally, I'd make an interface... let's call it IFilterable with a required method let's call Filter.

public interface {
    bool Filter( );
}

The each object in the collection could have a member of type IFilterable that defines the filter is should be using and you could then foreach through the list calling each ones' .Filter method. This way you could have a nice plug'n'play filtering scheme that any list could call.

Next I'd create a class extension for the List<IFilterable> class.

public static class ListEx {
        public static List<IFiltertable> Filter( this List<IFiltertable> list ) {
            List<IFiltertable> result = new List<IFiltertable>(list.Count);

            foreach ( IFiltertable item in list ) {
                if ( item.Filter() ) {
                    result.Add(item);
                }
            }
        }
    }

Now any List<IFilterable> I have I can just call Filter on it and get back a list of items that passed mustard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.