Linq Where Contains ... Keep the default order

I have a set of identification numbers for which I want to return some object, I do this using the linq statement with where the contains statement is used:

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 fine, except that I want to keep the order of the items in the returned collection the same as in the list that comes in. So, for example, if I had a list of identifiers: 14, 603, 388, I want the objects to be returned in the same order, and not in the order in which they were returned by the cache. Is there a way in the entity infrastructure to do this, or is there any way to do this that doesn't imply that I am writing a foreach loop?

thanks

+6
source share
2 answers

For everyone who is interested, I was able to get them to exit in the same order as the list by joining them, as Ray mentioned 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 your help and answers.

+1
source

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

Do LINQ method variables support relative element ordering?

Until you explicitly reorder or use an operator that, of course, reordered the initial order of the list, should be supported. Obviously, reordering the list for the where statement will be unnecessary.


The reason the above information is not relevant to this issue is given in the comments below. I would suggest changing the select output to a key / value pair, where the key is the identifier index in your list, and the value is your new object, then the orderBy key in the result set and select the value.

+3
source

Source: https://habr.com/ru/post/904678/


All Articles