Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Where Contains ... Keep default order

I have a collection of ID numbers that I wish to return some object for, I'm doing it by using a linq statement with a where that's using a contains statement:

var recentCats = (from i in EntityCache.Default.GetAll<Categories>()
                          where WebProfile.Current.RecentlyCreatedCategories.Contains(i.Id)
                          && BoundCategory.ParentItemClass.Id.Equals(i.ParentItemClass.Id)
                          select new CategoryInfo()
                          {
                              Category = i,
                              ClassId = i.ParentItemClass.Id,
                              ClassImage = NamedResourceManager.GetResourceBinary(i.ParentItemClass.NameResourceId)
                          });

This works perfectly fine, except that I want to keep the order of items in the returned collection the same as they were in the list that goes in. So for example if I had a list of IDs: 14, 603, 388, I want the objects that come back to be in the same order, not the order that they're returned by the cache. Is there any way in entity framework to do this, or any way to do it that doesn't involve me writing a foreach loop?

Thanks

like image 840
Mathew Collins Avatar asked Dec 29 '11 15:12

Mathew Collins


2 Answers

The Where Linq extension as with most extensions maintains the original order of the list.

Do LINQ's Enumerable Methods Maintain Relative Order of Elements?

As long as you do not explicitly reorder or use an operator that naturally would reorder the original list's order should be maintained. Obviously reordering the list for a where statement would be unneeded overhead.


The reason the information above does not apply to this question is in the comments bellow. I would suggest changing the output of the select to be a key/value pair, where the key is the index of the Id in your list, and the value is your new object, then orderBy the key on the resulting set, and select the value.

like image 65
Gent Avatar answered Sep 24 '22 06:09

Gent


For anyone interested, I was able to get them to come out in the same order as the list by joining them, as mentioned by Ray in the comments above.

var recentCats = (from i in WebProfile.Current.RecentlyCreatedCategories
                              join b in allCats
                                on i equals b.Id
                              where BoundCategory.ParentItemClass.Id.Equals(b.ParentItemClass.Id)
                              select ...

Thanks again for all your help & answers.

like image 38
Mathew Collins Avatar answered Sep 22 '22 06:09

Mathew Collins