LINQ Question, avoid selecting into from anonymous

I am new to LINQ I have a property,  Instead of selecting into an anonymous list then looping through and creating  a list of strings,  I would like to select right into a list of strings??? Is this possible?


         get {

                var navList = (
                from a in db.ArticleCategories
                select new
                {
                    a.Category
                }).ToList();

//would like to avoid this and select right int a list of strings to return

                List<String> ad = new List<String>();
                foreach (var v in navList)
                {
                    ad.Add(v.Category);
                }
                return ad;            
            }
Charles BaldoSoftware DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
You don't necessarily need the anonymous object creation, but the call to ToList makes complete sense. Personally, I would shorten this to use the method syntax of LINQ:

e.g.

ad = db.ArticleCategories.Select(a => a.Category).ToList();

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fernando SotoRetiredCommented:
Hi  charlesbaldo;

The reason you are getting a List of Anonymous type into the list is because you are using the new key word in the query. Remove the new keyword and just select Category from the ArticleCategories object as shown below.

 var navList = ( from a in db.ArticleCategories
                 select a.Category ).ToList();

Open in new window

0
Charles BaldoSoftware DeveloperAuthor Commented:
Perfect, the addition of the explanation of the new keyword effects made me understand it
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.