473,734 Members | 2,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dealing with NULL collection in Linq query


Hey everyone,

Is there a more elegant or cleaner way of accomplishing the following
null check?
List<stringmySt ring = null; //Purposely null list of strings to
show the example

XElement element = new XElement("Strin gs",
(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 7727
Deckarep wrote:
Is there a more elegant or cleaner way of accomplishing the following
null check?
List<stringmySt ring = null; //Purposely null list of strings to
show the example

XElement element = new XElement("Strin gs",
(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<stringmySt ring = 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<stringmyS tring = null; //Purposely null list of strings to
show the example

XElement element = new XElement("Strin gs",
(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<stringmySt ring = new List<string>();
and get rid of the tertiary?

Alternatively, something along these lines:

XElement element = new XElement("Strin gs",
(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 EnumerableExten sions {
public static IEnumerable<TEm ptyIfNull<T>(th is IEnumerable<T>
source) {
return source ?? Enumerable.Empt y<T>();
}
}

Now

List<stringstri ngs = null;
strings.EmptyIf Null().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 counterintuitiv e, 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
11191
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 rewrite everything in foreach) e.g. How can I make DataTable from it? Thx for help! var query =
1
10050
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 where t3.Id is null This query is having 2 left joins.
2
4807
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 table names might include "SomeTable1" or "SomeTable236" etc... Unfortunately when I try to use something like "from SomeTable + MyChangingNumber.ToString() in..." in my from clause it does not work. How can I set this up to use a range variable...
15
6035
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 find which items in A do not exist in B then:
2
1401
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 = q.Where(t =t.Field1==1);
3
1917
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 to WinForms' DataGridViews: http://blogs.msdn.com/aconrad/archive/2007/09/07/science-project.aspx The point is, the properties names extracted by the following lines:
1
8681
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 = from staff in Database.Staff where staff.Value.Passcode == txt_password.Text select staff;but i get the error Error 2 Cannot implicitly convert type...
2
6459
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 objects but continue to encounter the same error: Method 1: Anonymously Typed var results = (from c in uow.Contacts orderby c.LastName ascending, c.FirstName ascending select new {ID=c.Id, Title = c.Title, LastName=c.LastName,...
0
948
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 DataGrid control. Also, I need to let user to edit or delete data from DataGrid and update my database according this change. Here is a LINQ query: from d in App.glidusContext.tbl_users select new { d.userID, d.userName, d.userPassword }
1
2808
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, 'Package' and 'Product' (along with other classes). I've also created a Job class which houses a List<Package> and inside the Package class it houses a List<Product>. (NOTE): a Package is just a grouping of Products. so each Package could have 2...
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.