我有以下对象:
public class Result
{
public List<Recomendation> Recomendations { get; set; }
}
public class Recomendation
{
public List<Segment> Segments { get; set; }
}
public class Segment
{
public Leg OutBound { get; set; }
public Leg InBound { get; set; }
}
public class Leg
{
public TimeSpan TotalTime { get; set; }
public string Carrier { get; set; }
public int RefNumber { get; set; }
}
我有一个名为recommendations
我需要这样做:
recommendations
中出现字符串arr
,过滤Carrier
。我试过这样做:单独搜索入站:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => x.InBound.Carrier.Contains(arr))).ToList();
或单独搜索出站:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => x.OutBound.Carrier.Contains(arr))).ToList();
我想在 BOTH 入站和出站中搜索字符串arr
的出现次数。
问题是有时InBound可以为null或OutBound可以为null。我希望我的linQ可以在任何一种情况下工作。
答案 0 :(得分:4)
当入站或出站为空时,您需要确保代码不会中断。
var filteredList = recommendations.Where( r=>r.Segments.Any(x => ( x.OutBound != null && x.OutBound.Carrier.Contains(arr)) || (x.Inbound != null && x.InBound.Carrier.Contains(arr))).ToList();
答案 1 :(得分:2)
如果您使用的是C#6.0,则可以执行此操作:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => x?.InBound.Carrier.Contains(arr)
|| x?.OutBound.Carrier.Contains(arr) ))
.ToList();
答案 2 :(得分:0)
我不得不接受@raven的回答并对其进行修改。这是解决方案:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => ( x.OutBound != null && x.OutBound.Carrier.Contains(arr)) || (x.Inbound != null && x.InBound.Carrier.Contains(arr)))).ToList();