How do I order items within a C# List?

aspnet-scotland
aspnet-scotland used Ask the Experts™
on
Hi,

I have the below code. I am filling a list with data objects. I have an "Order" property but I'm not too sure how I can alter my code to sort the data objects on this order property?

public List<PhoenixWCF.Brand> BrandsByCategoryId(int intBrandCategoryId)
        {
            List<PhoenixWCF.Brand> brands = new List<PhoenixWCF.Brand>();

            foreach (var brand in Brands)
            {
                if(brand.BrandCategoryId == intBrandCategoryId)
                    brands.Add(brand);
            }

            return brands;
        }

Open in new window


Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
using System.Linq;

public List<PhoenixWCF.Brand> BrandsByCategoryId(int intBrandCategoryId)
        {
            List<PhoenixWCF.Brand> brands = new List<PhoenixWCF.Brand>();

            foreach (var brand in Brands)
            {
                if(brand.BrandCategoryId == intBrandCategoryId)
                    brands.Add(brand);
            }

            return brands.OrderBy(x=>x.Order);//or orderbydescending
        }

Commented:
brands.sort();

should sort it alphabetical but never heard of your type PhoenixWCF.Brand , maybe you can specify this a little further?
Top Expert 2011
Commented:
Just a small correction to p_davis code, since OrderBy / OrderByDescending return IEnumerable<T> you should call ToList() to return List<PhoenixWCF.Brand>.

using System.Linq;

public List<PhoenixWCF.Brand> BrandsByCategoryId(int intBrandCategoryId)
        {
            List<PhoenixWCF.Brand> brands = new List<PhoenixWCF.Brand>();

            foreach (var brand in Brands)
            {
                if(brand.BrandCategoryId == intBrandCategoryId)
                    brands.Add(brand);
            }

            return brands.OrderBy(x=>x.Order).ToList();//or orderbydescending
        } 

Open in new window

Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

Author

Commented:
I get the error "cannot implicitly convert type 'System.Linq.IOrderedEnumerable<PhoenixWCF.Brand>' to 'System.Collections.Generic.List<PhoenixWCF.Brand>'. An explicit conversion exists (are you missing a cast?)"?

Thanks.

Author

Commented:
Thanks wdosanjos!
thanks for the assist wdosanjos

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial