I am trying to use an Array instead of a list in my query. But I must get the count first before I can iterate through the objects returned from the database. Here is my code:
var FavArray = favorites.OrderByDescending(y => y.post_date).Skip((page - 1) * config.MaxRowsPerPage).Take(config.MaxRowsPerPage).ToArray();
int FavArrayCount = FavArray.Count(); //Is this a round trip to the database?
for (int y = 0; y < FavArrayCount; y++)
{
q = new PostType();
q.Title = FavArray[y].post_title;
q.Date = FavArray[y].post_date;开发者_如何学Go
q.PostID = FavArray[y].post_id;
q.Username = FavArray[y].user_username;
q.UsernameLowered = FavArray[y].user_username.ToLower();
q.CategoryID = FavArray[y].catid;
q.CategoryName = FavArray[y].name;
q.TitleSlug = FavArray[y].post_titleslug;
}
As you can see I need the count before I start iterating and I am worried that getting the count my make a trip to the database. Is this true?
FavArray.Count() will not round trip, because you have already converted it to an array, which is no longer "LINQ-ified".
Once you call ToArray
, any operations on the array that it returns will not go back to the server. (Unless you use a foreign key)
LINQ methods such as Count()
that you call on the array will use regular LINQ to Objects and will be completely unaware of SQL Server.
In addition to other comments (it definitely won't round trip; it's just an array), you can just use favArray.Length.
精彩评论