Owais Ahmed Owais Ahmed - 27 days ago 15
C# Question

Linq query based on the condition

I have to check col1 , col2 and col3 values and select the correct linq query.

This is how i am doing using if conditions.

public DataTable GetRawData(string col1, string col2, string col3)
{
IQueryable<IF_Table> result = null;
DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("DetailId");
dt.Columns.Add("Description");
DataRow row = null;
if (!string.IsNullOrEmpty(col1))
{
result = db.IF_Table.Where(x => x.col1 == col1);
}
if (!string.IsNullOrEmpty(col2))
{
result = db.IF_Table.Where(x => x.col2 == col2);
}
if (!string.IsNullOrEmpty(col3))
{
result = db.IF_Table.Where(x => x.col3 == col3);
}
if (!string.IsNullOrEmpty(col1) && !string.IsNullOrEmpty(col2))
{
result = db.IF_Table.Where(x => x.col1 == col1 && x.col2==col2);
}
if (!string.IsNullOrEmpty(col1) && !string.IsNullOrEmpty(col3))
{
result = db.IF_Table.Where(x => x.col1 == col1 && x.col3 == col3);
}
if (!string.IsNullOrEmpty(col2) && !string.IsNullOrEmpty(col3))
{
result = db.IF_Table.Where(x => x.col2 == col2 && x.col3 == col3);
}
if (!string.IsNullOrEmpty(col1) && !string.IsNullOrEmpty(col2) && !string.IsNullOrEmpty(col3))
{
result = db.IF_Table.Where(x =>x.col1==col1 && x.col2 == col2 && x.col3 == col3);
}
foreach ( var rowObj in result)
{
row = dt.NewRow();
dt.Rows.Add(rowObj.Id, rowObj.DetailId,rowObj.Description);
}
return dt;
}


Is there any other way to do without using too many if conditions? Any help or suggestion would be appreciated

Answer

Define base query which will return db.IF_Table. After that build the query around this result. This 3 if on your result should cover all of your cases.

        IQueryable<IF_Table> result = db.IF_Table;
        if (!string.IsNullOrEmpty(col1))
        {
             result = result.Where(x => x.col1 == col1);
        }
        if (!string.IsNullOrEmpty(col2))
        {
            result = result.Where(x => x.col2 == col2);
        }
        if (!string.IsNullOrEmpty(col3))
        {
            result = result.Where(x => x.col3 == col3);
        }

If you want empty DataTable to be return when all col1, col2, col3 are empty string or null. You can define bool variable fillTable and set it to true in the if statements. After the ifs you can check if(!fillTable)return dt;

Comments