ElementAt
The ElementAt operator returns an element at a given index from a collection. The collection is zero-based
and the return value is the element at the specified position in the source. In the following example, the
Contact table is queried looking for all contacts whose first name begins with the letter S. However, the
ElementAt operator is utilized to return the element at the first position by passing the value of 0 as a
parameter to the ElementAt operator.
DataContext context = new DataContext("Initial Catalog = AdventureWorks;Integrated
Security=sspi");
Table
contact = context.GetTable();
var query = from c in contact
where c.FirstName.StartsWith("S")
select c.FirstName;
listBox1.Items.Add(query.ElementAt(0));
78
Chapter 4: LINQ Standard Query Operators
Running this query will return the following:
Zheng
Be careful not to pass an index that is out of range; otherwise, the method throws an index out of range
error. If you??™re not sure of the index, use the ElementAtOrDefault. operator.
ElementAtOrDefault
The ElementAtOrDefault operator combines the ElementAt operator with some of the functionality of
the DefaultIfEmpty operator by returning the element at a specified index or a default value if the index
is out of range.
Pages:
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157