472,965 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,965 software developers and data experts.

Dealing with NULL collection in Linq query


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.

Thanks,
Jun 27 '08 #1
4 7696
Deckarep wrote:
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.
Don't use null references for collections, use empty collections instead:

List<stringmyString = new List<string>();

Edge case disappears. Also, a lambda is clearer here:

XElement element = new XElement(
"Strings",
myString.Where(s =s.StartsWith("S"))
);

--
J.
http://symbolsprose.blogspot.com
Jun 27 '08 #2
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.

Jun 27 '08 #3
Good point. I would use an empty collection if I could get away with
it. Unfortunately I'm using a system
that was not designed in this fashion so I often have to check for
null before knowing
if a collection is empty or not. :(

Thanks for the response tip on Lambda!
Jun 27 '08 #4
Deckarep wrote:
Good point. I would use an empty collection if I could get away with
it. Unfortunately I'm using a system
that was not designed in this fashion so I often have to check for
null before knowing
if a collection is empty or not. :(
If you really need to do this a lot, you can cheat your way around it:

public static class EnumerableExtensions {
public static IEnumerable<TEmptyIfNull<T>(this IEnumerable<T>
source) {
return source ?? Enumerable.Empty<T>();
}
}

Now

List<stringstrings = null;
strings.EmptyIfNull().Where(s =s.StartsWith("S"));

will work.

Disclaimer: while neat, I have no idea if this is inefficient compared to
null checks and if so, exactly how much. Also, calling a method on a
reference that's notionally null is obviously a little counterintuitive, so
many people would just call this another abuse of extension methods. :-)

--
J.
http://symbolsprose.blogspot.com
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: szwejk | last post by:
Hi! How to get result od dataTable from Linq query? I have typied DataSet and I want to join couple of tables. And I have a problem with change this result to DataTable type. (I don't want to...
1
by: silpa | last post by:
Hi, I have an SQL query like this select distinct t1.prodID from Table1 t1 left join Table2 t2 on t2.prodID = t1.prodID left join Table3 t3 on t3.serialno = t2.Id and t3.Qty = 0 ...
2
by: Joey | last post by:
I am querying a DataSet with LINQ. I am running into a problem when trying to construct my query because in the "from" clause I do not know the table name (range variable) until runtime. Possible...
15
by: shapper | last post by:
Hello, I have two Lists: A = {ID, Name} = { (Null, John), (Null, Mary), (Null, Andrew), (Null, Peter) } B = {ID, Name} = { (1, John), (2, Robert), (3, Angela), (4, Andrew) } I want to...
2
by: =?Utf-8?B?Tmljaw==?= | last post by:
Hello, I need some assistance with a LINQ query. I've got a simple query: var q = from t in db.Table1 select t; Based on user input I'm adding some where clauses: if (condition1) q =...
3
by: Vivien Parlat | last post by:
Hello, I am currently using VB.Net 2008 express. I use linq to perform queries on a database, and I'm using the following link's source to convert those queries into DataTables i can then bind...
1
by: alex21 | last post by:
Ok i am trying to use a Linq query to access a dictionary. public static Dictionary<string, Client> Clients = new Dictionary<string, Client>();Using this Linq query: IEnumerable<Staff> loginquery...
2
by: scott1010 | last post by:
Hello I am having problems with a Linq query. I need to return an ID field which is of type GUID (c.Id) along with other fields of type String. I have tried both anonymous types and strongly typed...
0
by: James Folkerman | last post by:
Hi. I have SQL Server database that is connected to my WPF desktop-based application via ADO.NET Entity Framework. Now I need get content of one of the table via LINQ query and show it in...
1
by: kgkgkg | last post by:
Hey everyone, I've dealt with some simple LINQ queries before, but am not sure how to tackle this one... I've got a project I'm working on where I'm dealing with two classes I've created,...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.