You know from previous examples that this query will return some values; however, the
DefaultIfEmpty operator is used in case an empty sequence is returned.
DataContext context = new DataContext("Initial Catalog = AdventureWorks;Integrated
Security=sspi");
Table
contact = context.GetTable();
var query = from c in contact
where c.FirstName.StartsWith("Z")
select c.FirstName;
foreach (string item in query.DefaultIfEmpty())
listBox1.Items.Add(item);
When the query is executed, all first names that begin with the letter Z are returned. Modify the query,
changing the criteria to look for first names that begin with the letters ZZ:
var query = from c in contact
where c.FirstName.StartsWith("ZZ")
select c.FirstName;
foreach (string item in query.DefaultIfEmpty("none"))
listBox1.Items.Add(item);
When this query runs, it does not find any first names that begin with the letters ZZ, so nothing will be
returned, and the DefaultIfEmpty operator instructs the query to produce an empty sequence.
Just as a reminder: reference and nullable types have a default value of null.
Pages:
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156