Add(query.FirstOrDefault());
You can also add specific criteria when using this operator. The following, for instance, returns
the first element that satisfies a specific condition, the first name whose length is greater
than 5:
listBox1.Items.Add(query.FirstOrDefault(name => name.Length > 5));
LastOrDefault
The LastOrDefault operator returns the last element from a collection, or a default value if no element
is found. Here??™s another example that queries the Contact table for all contacts whose first name begins
with the letters ZZ. It uses the LastOrDefault operator to return the last element from the returned
collection. If the element is not found then a default value is returned.
80
Chapter 4: LINQ Standard Query Operators
DataContext context = new DataContext("Initial Catalog=AdventureWorks;Integrated
Security=sspi");
Table
contact = context.GetTable();
var query = from c in contact
where c.FirstName.StartsWith("ZZ")
select c.FirstName;
listBox1.Items.Add(query.LastOrDefault());
You can also add specific criteria when using this operator, such as the following, which returns the last
element that satisfies a specific condition, the first name whose length is less than 5.
Pages:
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161