Home > Back-end >  How to avoid using IF-Else and use inline if condition inside the .where() function?
How to avoid using IF-Else and use inline if condition inside the .where() function?

Time:10-11

 q = q.Where(s => 
                    !matchingRecords.Contains(s.Id)
                    || (s.SecId != null)
                 );

but the matchingrecords could be null or having 0 items in it since it's a list. So, in that case it would fail in the above code. I want to check this contains only if the matching records is not null and have some elements else not.

One way is to put IF-Else block and repeat the code but I want to do it inline, how ?

CodePudding user response:

 q = q.Where(s => (matchingRecords != null && matchingRecords.Count > 0 && 
                !matchingRecords.Contains(s.Id))
                || (s.SecId != null)
             );

The condition matchingRecords != null && matchingRecords.Count > 0 will ensure !matchingRecords.Contains(s.Id) is executed only if matchingRecords has at least 1 record

CodePudding user response:

So, if input conditions are:

  • matchingRecords is not null;
  • matchingRecords not empty (contains elements, .Count > 0);
  • no if-else usage allowed;

could it be done through ternary?

var list = matchingRecords?.Count > 0 ?
           q.Where(s => !matchingRecords.Contains(s.Id) && s.SecId != null).ToList()
           : new List<Record>();

matchingRecords? checks for null and .Count after checks for "not empty". If-else replaced with ternary, which would filter collection using Where or return new List<Record> on else case.

Sample:

class Program
{
    private static List<int> matchingRecords; // It is null, we "forget" to initialize it

    static void Main(string[] args)
    {
        var list = new List<Record>() 
        {
            new Record { Id = 0, SecId ="Some SeqId" },
            new Record { Id = 1, SecId = null },
            new Record { Id = 2, SecId = "Another SeqId" },
        };

        var filteredRecords = FilterRecords(list);
    }

    static IEnumerable<Record> FilterRecords(IEnumerable<Record> q)
    {
        return matchingRecords?.Count > 0 ? // Checking for not null and not empty (if case)
               q.Where(s => !matchingRecords.Contains(s.Id) && s.SecId != null)
               : q; // else case
    }
}

public class Record
{
    public int Id { get; set; }
    public string SecId { get; set; }
}

Not sure that properly reproduced your situation, so correct me if something is wrong.

  • Related