简体   繁体   中英

How can I get the first string out of a list in C#?

I have this string:

   foreach (string error in result.Errors)

When I check it says that result.Errors is IEnumerable

I tried to get the first of these like this but it does not work:

   var error1 = result.Errors[0];

Can someone give me advice on what I am doing wrong?

Something like this:

  String error1 = result.Errors.FirstOrDefault();

if there's a possibility that result itself can be null , than you have to add an additinal check:

  String error1 = result == null ? null : result.Errors.FirstOrDefault();

in all the cases, if error1 == null , there're no errors , otherwise, error1 is the first one .

Possibly duplicate of How do I get the first element from an IEnumerable<T> in .net?

Before all that check for null:

if(result.Errors == null) 
   return null;

Try to use linq

 result.Errors.First() ?

if you are not sure if there're any errors: use

result.Errors.FirstOrDefault() 

it will return null if collection is empty

And one more option

result.Errors.ElementAt(0)

or hard code:

new List<string>(result.Errors)[0] // but it's not pretty at aall
//or as poined bellow via extensions
result.Errors.ToList()[0]
result.Errors.ToArray()[0]

Try this

var error1 = result.Errors.First().ToString();

OR

var error1 = result.Errors.FirstOrDefault();

You can use LINQ extension method FirstOrDefault()
which return null (in case of String ) if collection is empty

string first = result.Errors.FirstOrDefault();

.First() will throw exception if colleciton is empty

Try This.If string is NULL empty will be returned.

var error1 = result.Errors.FirstOrDefault() != null ? result.Errors.FirstOrDefault():string.Empty;

OR

 var error1 = !string.IsNullOrEmpty(result.Errors.FirstOrDefault()) ? result.Errors.FirstOrDefault():string.Empty;

Try this First()

result.Errors.First();

or if result.Errors doesn't contain anything use FirstOrDefault

result.Errors.FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM