简体   繁体   中英

Custom Comparer in LINQ query to sort strings/numerics

I've written a custom comparer that sorts strings and numeric. This all works fine.

However I'm rewriting my whole BLL to use LINQ where possible as I do like the syntax. Now i'm stumbling onto using my custom comparer. As LINQ syntax (query based) will not allow to use custom comparers Im now using method based LINQ.

But in order to make it to work, I need to do an intermediate ToList(), which again works fine, but looks somewhat weird to me?

        var areas = cc.Areas.Where(a => a.ProjectId == ProjectId).ToList()
                            .OrderBy(a => a.UnitNumber, new Common.Comparers.StringNumericComparer());

Now i'm unsure if this has to do with the SQL query to be executed first and then the results sorted in my C# code side, but this is beyond my knowledge. Does ToList() force the first part of the linq query to be executed on the database?

是的.ToList()强制您的Areas被加载,并且排序在内存中进行。

Yes your understanding is correct. Until the .ToList() it is an IQueryable. On ToList() a database query is fired and the results are fetched in memory and then a sort occurs on the List.

Your comparer cannot execute before this since it does not translate to an SQL query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM