You can use LINQ for querying a collection in a simpler way.
Let's take as an example the following collection:
var objCollection = (ICollection<object>) new List<object>
{
"Good Morning",
"Good Afternoon",
"Good Night"
};
Now we can extract the first, last or an item at a specific index with the following:
var firstItem = objCollection.First(); // returns "Good Morning"
var lastItem = objCollection.Last(); // returns "Good Night"
var itemAtIndex1 = objCollection.ElementAt(1); // returns "Good Afternoon"
There is also OrDefault
variants of all the previous. The difference is that First
will throw an exception if objCollection
has no items, but FirstOrDefault
will simply return default(object)
(which is null
by the way) if objCollection
has no items.
For putting an example, this is how OrDefault
variants can be used:
var firstItem = objCollection.FirstOrDefault(); // returns "Good Morning"
var lastItem = objCollection.LastOrDefault(); // returns "Good Night"
var itemAtIndex99 = objCollection.ElementAtOrDefault(99); // returns null, because `objCollection` has only three items and the index 99 doesn't exist on it
In the scenario of greetingRecommendation.Resolution.Values
, something like the following can be used for retrieving the first item of the collection:
var greeting = greetingRecommendation.Resolution.Values.FirstOrDefault() as string;
Let's assume that Values
property is of type ICollection<object>
.
That line will ensure that:
- If
Values
property has no items, no exception will be thrown, and default(object)
would be returned.
- The first item in
Values
property will be safely casted to a string
, to avoid issues if it contains a value that can not be casted to string
. If the value can not be casted, default(string)
(which is null
) will be returned.
- The variable
greeting
will contain either null
or a string
with the first value of the Values
property.
Do not forget to add a using System.Linq;
in the using directives to be able to use LINQ.
I've prepared a .NET Fiddle in the following link for seeing such LINQ operations in action: