Linq dynamic AND OR statements
Tech-Today

Linq dynamic AND OR statements


You usually need this on search form where you have to add a condition if a field is filled or not.

This is how I do it:

public static List Search(SearchViewModel param)
{
IQueryable matches = EntityMdl.SellOutMobiles;

if (!string.IsNullOrEmpty(param.Client))
{
var clientId = Convert.ToInt32(param.Client);
matches = matches.Where(p => p.ClientId == clientId);
}

if (!string.IsNullOrEmpty(param.Branch))
{
var branchId = Convert.ToInt32(param.Branch);
if (branchId != 0)
matches = matches.Where(p => p.BranchId == branchId);
}

if (!string.IsNullOrEmpty(param.InvoiceNo))
{
matches = matches.Where(p => p.InvoiceNo.Contains(param.InvoiceNo));
}

if (!string.IsNullOrEmpty(param.SerialNo))
{
matches = matches.Where(p => p.SerialNo.Contains(param.SerialNo));
}

var query = (from aa in matches
join bb in EntityMdl.Dealers on aa.ClientId equals bb.DealerId
join cc in EntityMdl.Branches on aa.BranchId equals cc.BranchId
join dd in EntityMdl.Models on aa.ModelId equals dd.ModelId
join ee in EntityMdl.PaymentTypes on aa.PaymentType equals ee.Code
select new SearchResultViewModel
{
Client = bb.Dealer1,
Branch = cc.Branch1,
Date = aa.Date,
InvoiceNo = aa.InvoiceNo,
SerialNo = aa.SerialNo,
Model = dd.Model1,
Price = aa.Price,
PaymentType = ee.Text
}).ToList();

return query;
}




- How To Enable Jersey Servlet In Web.xml
To enable jersey web service in your web application, simply copy and paste the code below in your web.xml file. <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>...

- How To Execute A Group By And Sum Query In Entity Framework
The following code is the native sql with the converted code in entity framework. It queries the sum of quantity group by branch, model, year and week no. //native sql select weekyear, weekno, branchid, modelid, sum(quantity) from selloutmobiles where...

- How To Write Left Join Sql On Entity Framework
In every limitation there is always a work around. For this specific limitation on entity framework 3.5 not having a left join. This is what I came up: For example you want to: SQL: select * from contact a left join country c on a.contactid=c.contactid...

- C# Converting A Date To Timestamp And How To Create An Md5 Function
A always use these 2 methods so I'm gonna paste them here. I don't remember if I change some lines in these code but I'm sure I got them from Microsoft hmmm already forget about it. DateTime -> TimeStamp /// /// method for converting a System.DateTime...

- Download Image Given A Url In C# Using The System.net.httpwebrequest Class
Saves image url object into the local machine /// /// Saves the list of url object into the output directory /// /// list of url path /// root directory that will be used for saving internal static void PhotoDownloader(ArrayList aList, string outputDir)...



Tech-Today








.