On Thu, 15 May 2008 10:44:57 -0700 (PDT), Deckarep
<de******@gmail.comwrote:
>
Hey everyone,
Is there a more elegant or cleaner way of accomplishing the following
null check?
List<stringmyString = null; //Purposely null list of strings to
show the example
XElement element = new XElement("Strings",
(myString != null) ?
(from string s in myString
where s.StartsWith("S")
select s) : null
);
This XElement yields the following result: <Strings/and empty
Element.
I like that I can write linq to xml in nested declarations like this.
What I don't like now...is doing the null
check with the tertiary starts making the code ugly and less
readable. I know how to handle null values
when some of the contents in the collection may be null but what if
your collection is null itself??
If there's a better more Linq integrated way of handling this that
would be great.
Hmm, do you need to be able to differentiate between a null myString
and an empty list of strings?
That is, could you use List<stringmyString = new List<string>();
and get rid of the tertiary?
Alternatively, something along these lines:
XElement element = new XElement("Strings",
(myString ?? new List<string>()).Where(s =s.StartsWith("S")));
Neither strike me as a lot cleaner or more elegant though :-)
Regards,
Gilles.