Link to home
Start Free TrialLog in
Avatar of John Bolter
John Bolter

asked on

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.
Avatar of kaufmed
kaufmed
Flag of United States of America image

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

Avatar of John Bolter
John Bolter

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial