HelpASisterOut
HelpASisterOut

Reputation: 3185

Condition inside linQ Where condition

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:

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

Answers (3)

raven
raven

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

HelpASisterOut
HelpASisterOut

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

ocuenca
ocuenca

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

Related Questions