I often refer to IEnumerable & lt; T & gt; I want to get the first element of .net in
, and I have not found a good way to do this. I have come up with the best:
foreach (Elm e eMermerelabel) {// E do something with brake; }
Yuk! So, what is a good way to do this?
If you can use LINQ you can use:
< Code> var e = enumerable.First ();
This will throw an exception, though the calculable is empty: in which case you can use:
var e = enumerable.FirstOrDefault ();
If you can not use LINQ, then your approach is technically correct and using IEnumerator (EElformer & lt; Elem & gt; enumer = enumerable.GetEnumerator ()) EDIT: Thank you for telling me that After using my First and default ()
will return default (t)
if the calculable is empty, which will be null < Default 'zero-value' for / code> for reference types or for price types.
is not different from making a calculator using GetEnumerator to get the first result
And moveNext
methods (this example assumes that there is a IEnumerable & lt; Elem & gt;
):
Elem E = myDefault; (If (enumer.MoveNext ()) e = enumer.Current;}
. Single ()
in the comments; It will also work, if you are expecting to keep an element in your calculation - though it will throw an exception if it is either empty or from an element Large is a compatible single default ()
method that covers this scenario equally as first and default ()
. It is possible that single default ()
can also throw an exception in the case where there are more than one item in the number. IEnumerator
object - I have edited the non-LINQ example to display this keyword using to apply
the keyword.
Comments
Post a Comment