LINQ question

Hi, is there a way in LINQ other than using an if statement before the LINQ to get select2 below populated with an empty list? As the code below stands at the moment, it errors at runtime.

            List<string> list1 = new List<string> { "one", "two" };
            var select1 = from l1
                            in list1
                          select "value-" + l1;

            List<string> list2 = null;
            var select2 = from l2
                            in list2
                          select "value-" + l2;

Open in new window


At the moment I use the code below to overcome the problem. Is this how you have to do it?

            List<string> list2 = null;
            var select2 = from l2
                            in list2 ?? new List<String>()
                          select "value-" + l2;

Open in new window


Thank you.
John BolterAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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:
That's how I would do it if I *had* to use that code, but I must ask:  Why initialize list2 to null if you're just going to refer to it in the subsequent query immediately following?
käµfm³d 👽Commented:
P.S.

And I must be misunderstanding your goal here, because as it stands, there won't be anything in select2... I'm wondering if you are really wanting this:

var select2 = Enumerable.Empty<string>();

Open in new window

John BolterAuthor Commented:
Hi, and thanks.

> Why initialize list2 to null if you're just going to refer to it
> in the subsequent query immediately following?

It is just showing what I want to do without a whole lot of other irrelevant code. The list<string> is actually returned from a method, and I do stuff with it before the LINQ.
käµfm³d 👽Commented:
OK, then the coalesce operator ( ?? ) is probably what I'd use.

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
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.