The SingleOrDefault operator returns the single
element from the returned collection.
DataContext context = new DataContext("Initial Catalog=AdventureWorks;Integrated
Security=sspi");
Table
contact = context.GetTable();
var query = from c in contact
where c.LastName.StartsWith("Kobylinski")
select c.FirstName;
listBox1.Items.Add(query.SingleOrDefault());
When this query runs, the name Andrew is written to the list box, because that??™s the only contact who
has the last name of Kobylinski. Change the query to the following and rerun the query:
var query = from c in contact
where c.LastName.Equals("Kleinerman")
select c.FirstName;
When this query executes, you get an error stating that the sequence contains more than one element
because there are two contacts whose last name equals ??????Kleinerman.??™??™
You can also specify criteria to this operator as a parameter, as shown here:
var query2 = from c in contact
select c.LastName;
listBox1.Items.Add(query2.SingleOrDefault(con => con.Equals("Kobylinski")));
Equality Operators
Equality operators compare two sequences to check if their corresponding elements are equal.
Pages:
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164