[英]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 当我检查它说那result.Errors是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: 如果
result
本身可以为null
,则必须添加附加检查:
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 . 在所有情况下,如果
error1 == null
,则没有错误 ,否则, error1
是第一个 。
Possibly duplicate of How do I get the first element from an IEnumerable<T> in .net? 可能与如何从.net的IEnumerable <T>中获取第一个元素重复?
Before all that check for null: 在所有检查之前,检查null:
if(result.Errors == null)
return null;
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 如果collection为空,它将返回null
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()
您可以使用
LINQ
扩展方法FirstOrDefault()
which return null
(in case of String
) if collection is empty 如果collection为空,则返回
null
(对于String
)
string first = result.Errors.FirstOrDefault();
.First()
will throw exception if colleciton is empty 如果colleciton为空,则First
.First()
将引发异常
Try This.If string is NULL
empty will be returned. 试试这个,如果字符串为
NULL
将返回空。
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()
试试这个
First()
result.Errors.First();
or if result.Errors
doesn't contain anything use FirstOrDefault
或者如果
result.Errors
不包含任何使用FirstOrDefault
result.Errors.FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.