Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

c# - LINQ multiple order by

I have created a function that has the follwing parameter:

List<Expression<Func<CatalogProduct, bool>>> orderBy = null

This parameter is optional, If it is filled it should create a order by and than by constuction for me, so that I can order the result on the SQL server.

I tried:

            IOrderedQueryable temp = null;
            foreach (Expression<Func<CatalogProduct, bool>> func in orderBy)
            {
                if (temp == null)
                {
                    temp = catalogProducts.OrderBy(func);
                }
                else
                {
                    temp = temp.ThanBy(func);
                }
            }

But the than By is not reconized. Does someone know how I can solve this problem?


I changed it to .ThenBy() but this is only allowed directly after the .OrderBy() and not on a IOrderedQueryable

so temp = catalogProducts.OrderBy(func).ThenBy(func); is allowed but temp = catalogProducts.OrderBy(func); temp = temp.ThenBy(func); issn't

Any other suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two problems; firstly, ThanBy should be ThenBy; secondly, ThenBy is only available on the generic type, IOrderedQueryable<T>.

So change to:

        IOrderedQueryable<CatalogProduct> temp = null;
        foreach (Expression<Func<CatalogProduct, bool>> func in orderBy) {
            if (temp == null) {
                temp = catalogProducts.OrderBy(func);
            } else {
                temp = temp.ThenBy(func);
            }
        }

and you should be sorted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...