Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 等价于使用LINQ在IEnumerable中搜索_C#_Linq - Fatal编程技术网

C# 等价于使用LINQ在IEnumerable中搜索

C# 等价于使用LINQ在IEnumerable中搜索,c#,linq,C#,Linq,有没有一种更简短、更优雅的方式来使用LINQ编写以下内容 var actorName = string.Empty; foreach (var myProperty in myProperties) { if (myProperty .PropertyName == "ActorName") { actorName = myProperty .PropertyValue; break; }

有没有一种更简短、更优雅的方式来使用LINQ编写以下内容

 var actorName = string.Empty;
 foreach (var myProperty in myProperties)
 {
       if (myProperty .PropertyName == "ActorName")
       {
             actorName = myProperty .PropertyValue;
             break;

       }

  }
如果找不到任何内容,这将给出NPE(
FirstOrDefault
默认返回
null

要解决这一问题,请使用两种说法:

var actor = myProperties
                .FirstOrDefault(x => x.PropertyName == "ActorName");

var actorName = actor == null ? string.Empty : actor.PropertyValue; 
如果找不到任何内容,这将给出NPE(
FirstOrDefault
默认返回
null

要解决这一问题,请使用两种说法:

var actor = myProperties
                .FirstOrDefault(x => x.PropertyName == "ActorName");

var actorName = actor == null ? string.Empty : actor.PropertyValue; 

除了Jeroen的回答。。首先检查
null
更安全。。因为当没有匹配项时,
FirstOrDefault
返回
null

var actor = myProperties
            .FirstOrDefault(x => x.PropertyName == "ActorName");

if (actor != null)
    actorName = actor.PropertyValue;

除了Jeroen的回答。。首先检查
null
更安全。。因为当没有匹配项时,
FirstOrDefault
返回
null

var actor = myProperties
            .FirstOrDefault(x => x.PropertyName == "ActorName");

if (actor != null)
    actorName = actor.PropertyValue;

纯粹的LINQ版本,尽管我更喜欢Simon的答案

var actorName = myProperties
    .Where(x => x.PropertyName == "ActorName")
    .Select(x => x.PropertyValue)
    .Concat(new[]{ string.Empty })
    .First();

纯粹的LINQ版本,尽管我更喜欢Simon的答案

var actorName = myProperties
    .Where(x => x.PropertyName == "ActorName")
    .Select(x => x.PropertyValue)
    .Concat(new[]{ string.Empty })
    .First();

等待如果“违约”发生了怎么办?那太美了!谢谢最简单的解决方案是使用两条语句并检查
null
值。我不能马上想出一个方法来检查这个内联,所以我会等待,看看是否有其他人这样做。如果可能的话,我会移除这个。等等。。如果“违约”发生了怎么办?那太美了!谢谢最简单的解决方案是使用两条语句并检查
null
值。我不能马上想出一个方法来检查这个内联,所以我会等待,看看是否有其他人这样做。如果可能的话,我会移除这个。