Pages

Tuesday, January 14, 2014

Converting Lists to Collections in C# and Using Linq on it

All right guys, this one is one of the shortest blog post I am doing today and hope it helps people like me who wasted almost few minutes searching for solution on this.

Basically .NET Framework offers us too many collections however two of those are
1. List
2. Collection

We all know Linq, i.e. this nice and slick feature of .NET to query various collections however when it comes to Collections then we get this famous typecasting error
i..e Cannot convert IEnumerable to Collection etc etc..

Well, after several minutes of discussion with my brainy peers and some search on internet here is what I have done

Its a workaround which works in two steps
1. Convert your Collection to List and perform Linq on it.
2. Convert back your List to Collection. How? here we go

Collection<Entity> collection = new ObservableCollection<Entity>(collection.ToList().Distinct());

And you are done.

Hope this helps someone.

No comments:

Post a Comment