Reputation: 3185
I have the following object:
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; }
}
I have a List called recommendations
I need to do this:
recommendations
by occurrence of a string arr
in Carrier
, inside either the outbound or the inbound objects. I tried doing this:Search Inbound alone:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => x.InBound.Carrier.Contains(arr))).ToList();
or search outbound alone:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => x.OutBound.Carrier.Contains(arr))).ToList();
I want to search for the occurrence of the string arr
in BOTH inbound and outbound.
The problem is sometimes InBound can be null or OutBound can be null. I want my linQ to work in either cases.
Upvotes: 3
Views: 1537
Reputation: 2431
You need to make sure that the code won't break when either Inbound or Outbound is null.
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();
Upvotes: 5
Reputation: 3185
I had to take @raven's answer and modify it a bit. Here's the solution:
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();
Upvotes: 0
Reputation: 39386
You could do this if you are using C# 6.0:
var filteredList = recommendations.Where( r=>r.Segments.Any(x => x?.InBound.Carrier.Contains(arr)
|| x?.OutBound.Carrier.Contains(arr) ))
.ToList();
Take a look Null-conditional Operators
Upvotes: 2