Sevval Kahraman
Sevval Kahraman

Reputation: 1301

if control in linq?

This query is what I got:

var hede = (from customer in _customerRepository.Table
  join source in _sourcedefinitionepository.Table on customer.SourceCode equals source.SourceCode
  select new {Customer = customer, source.SourceName} 

And then I wrote this:

if (agencyName ! = null )
    hede = hede.Where(p => p.Customer.Name.StartsWith(agencyName));

How can i put the if code into first part of code?

Upvotes: 0

Views: 117

Answers (2)

Reza Jenabi
Reza Jenabi

Reputation: 4279

You can use the following code

 var hede = _customerRepository.Table.Join(_sourcedefinitionepository.Table, 
            x => x.SourceCode, 
            y => y.SourceCode, 
            (customer, source) => new { customer, source.SourceName})
            .Where(p => agencyName == null  ||
            (p.customer.Name.Any(f => p.customer.Name.StartsWith(agencyName))));

lambda code

var hede =from customer in _customerRepository.Table
                    join source in _sourcedefinitionepository.Table 
                    on customer.SourceCode equals source.SourceCode
            where agencyName == null || customer.Name.Any(f => customer.Name.StartsWith(agencyName))
                    select new { Customer = customer, source.SourceName };

Upvotes: 1

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

You can achieve it in this way

where agencyName  == null || customer.Name.StartsWith(agencyName));

Full query

var hede = (from customer in _customerRepository.Table
join source in _sourcedefinitionepository.Table on customer.SourceCode equals source.SourceCode
where agencyName  == null || customer.Name.StartsWith(agencyName))
select new {Customer = customer, source.SourceName} 

Updated Using lamda.

var hede = _customerRepository.Table.Join(_sourcedefinitionepository.Table, c => c.SouceCode , s => s.SourceCode,
                (c, s) => new
                {
                    Customer = c, 
                    s.SourceName
                })).Where(p => agencyName  == null || p.Customer.Name.StartsWith(agencyName)).ToList();

Upvotes: 4

Related Questions