Using IEnumerables with a Grid
I have an IEnumerable<GridItem> items
containing a list of thousands of items, each item containing some seriously complex calculated properties.
To keep performance up, the list can be viewed one page (20 records) at a time in a webpage grid.
PROBLEM
If you want to display the grid's paging information to the user, you need to find out how many total records there are i.e.items.Count()
which t开发者_StackOverflow社区hen basically converts the IEnumerable
into a List
evaluating ALL the properties and taking ages to do so!
Is there a way around this?
In general, you do not have to evaluate properties of GridItem when iterating over IEnumerable. You could skip calculations until they are used first, or evaluate properties lazily (when they are read).
I mean to say that, you could either have a function like Calculate() that is calculated after construction or you could have have calculations done in the getter of properties/relevant functions.
You could also obtaint the count (total number) or records from the source of GridItem (database for example) instead which IMO is better.
How about making your own class which inherits from GridItem (which allows you to still bind it to the grid), and also implements an interface? When you need to get the count, you could cast the IEnumerable to the interface, and get the list for that. I think that would bypass calling the ToList of your proper MyGridItem class.
For example:
public class MyGridItem : GridItem, IMyGridItem { } public interface IMyGridItem { // Just an empty interface } // Code to get the count IEnumerable<MyGridItem> items; List<IMyGridItem> castList = items.Cast<IMyGridItem>().ToList(); int count = castList.Count;
PROBLEM SOLVED
Performing a Count()
on an IEnumerable
will enumerate the collection. However, this is NOT the same as converting the IEnumerable
to a List
e.g. .ToList()
(which would in fact evaluate all properties of entities in the list)
End of the day, IEnumerable.Count() may be slow but thats not because its enumerating all the IEnumerable objects' properties
(PLEASE somebody reprimand me if this understanding is not correct?!)
精彩评论