473,804 Members | 4,181 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

LINQ and dynamic where clauses

I am trying to set up a dynamic search using linq. I believe the syntax is
correct, but cannot confirm it because when I try to cast my
Session[“Employees”] from a List<to IQueryable<>, I get a cast error
“Unable to cast object of type System.Collecti ons.Generic.Lis t to type
System.Linq.IQu eryable”. Is there a way to cast List<to IQueryable<>, or is
there a different way I need to be doing this?

protected void btnSearch_Click (object sender, EventArgs e)
{
try
{
if (Session["Employees"] != null)
{
IQueryable<Busi nessLogic.Servi ces.UserProfile employees =
(IQueryable<Bus inessLogic.Serv ices.UserProfil e>)(List<Busine ssLogic.Service s.UserProfile>) Session["Employees"];

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
employees.Where (c =c.Username ==
txtSearchCriter ia.Text);
break;

case "Email":
employees.Where (c =c.EmailAddress ==
txtSearchCriter ia.Text);
break;

default: //LastName
employees.Where (c =c.Person.LastN ame ==
txtSearchCriter ia.Text);
break;
}

BindGrid(employ ees.Select(c =>
c).ToList<Busin essLogic.Servic es.UserProfile> ());
}
else
{
List<BusinessLo gic.Services.Us erProfileemploy ees = null;
Shared.Business Logic.UserSearc hFilter filter = new
UserSearchFilte r();

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
filter.Username = txtSearchCriter ia.Text;
break;

case "Email":
filter.EmailAdd ress = txtSearchCriter ia.Text;
break;

default: //LastName
filter.LastName = txtSearchCriter ia.Text;
break;
}

PagedResult<Bus inessLogic.Serv ices.UserProfil epagedResult =
SearchEmployees (filter);
employees =
pagedResult.Res ults.ToList<Bus inessLogic.Serv ices.UserProfil e>();
BindGrid(employ ees.ToList<Busi nessLogic.Servi ces.UserProfile >());
}
}
catch (ThreadAbortExc eption) { }
catch (Exception ex) { ExceptionHelper .Publish(ex); }
}

Sep 19 '08 #1
4 3607
Hi Mike, there are several ways of doing this. But I got this way
working...

I hope it helps,

cheers, mesut
objDataContext = DatabaseFactory .GetLinq();
List<Linq.tblCo stLocalTable;
var query = (from costing in objDataContext. tblCosts
select costing);

//the where code below (2 lines) are
replace by dynamic where
//where costing.Product ID == productID &&
//costing.Busines sUnit == businessUnit

if (productID != 0) query = query.Where(cos t =>
cost.ProductID == productID);
if (!string.IsNull OrEmpty(busines sUnit)) query =
query.Where(cos t =cost.BusinessU nit == businessUnit);

LocalTable = query.ToList();

return LocalTable;
Sep 19 '08 #2
Thanks for the reply, but I am not able to get it to work yet. Can you, or
anyone, offer some input.

Below is what I tried...also I decided that I needed to use SQLMethods.Like

List<.BusinessL ogic.Services.U serProfileemplo yees =
(List<.Business Logic.Services. UserProfile>)Se ssion["Employees"];
var query = from p in employees
select p;

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
query.Where(c =SqlMethods.Lik e(c.Username, "%" + txtSearchCriter ia.Text
+ "%"));
break;

case "Email":
query.Where(c =SqlMethods.Lik e(c.EmailAddres s, "%" +
txtSearchCriter ia.Text + "%"));
break;

default: //LastName
query.Where(c =SqlMethods.Lik e(c.Person.Last Name, "%" +
txtSearchCriter ia.Text + "%"));
break;
}

employees = query.ToList();

BindGrid(employ ees);
"mesut" wrote:
Hi Mike, there are several ways of doing this. But I got this way
working...

I hope it helps,

cheers, mesut
objDataContext = DatabaseFactory .GetLinq();
List<Linq.tblCo stLocalTable;
var query = (from costing in objDataContext. tblCosts
select costing);

//the where code below (2 lines) are
replace by dynamic where
//where costing.Product ID == productID &&
//costing.Busines sUnit == businessUnit

if (productID != 0) query = query.Where(cos t =>
cost.ProductID == productID);
if (!string.IsNull OrEmpty(busines sUnit)) query =
query.Where(cos t =cost.BusinessU nit == businessUnit);

LocalTable = query.ToList();

return LocalTable;
Sep 19 '08 #3
the where clause in a Linq query does not set a property, its a method
(actually an extension method) that returns another IQueryable object that
the Select method (which also return an IQueryable) can be called on. your
code is throwing away the results of the Where.


-- bruce (sqlwork.com)
"Mike Collins" wrote:
I am trying to set up a dynamic search using linq. I believe the syntax is
correct, but cannot confirm it because when I try to cast my
Session[“Employees”] from a List<to IQueryable<>, I get a cast error
“Unable to cast object of type System.Collecti ons.Generic.Lis t to type
System.Linq.IQu eryable”. Is there a way to cast List<to IQueryable<>, or is
there a different way I need to be doing this?

protected void btnSearch_Click (object sender, EventArgs e)
{
try
{
if (Session["Employees"] != null)
{
IQueryable<Busi nessLogic.Servi ces.UserProfile employees =
(IQueryable<Bus inessLogic.Serv ices.UserProfil e>)(List<Busine ssLogic.Service s.UserProfile>) Session["Employees"];

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
employees.Where (c =c.Username ==
txtSearchCriter ia.Text);
break;

case "Email":
employees.Where (c =c.EmailAddress ==
txtSearchCriter ia.Text);
break;

default: //LastName
employees.Where (c =c.Person.LastN ame ==
txtSearchCriter ia.Text);
break;
}

BindGrid(employ ees.Select(c =>
c).ToList<Busin essLogic.Servic es.UserProfile> ());
}
else
{
List<BusinessLo gic.Services.Us erProfileemploy ees = null;
Shared.Business Logic.UserSearc hFilter filter = new
UserSearchFilte r();

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
filter.Username = txtSearchCriter ia.Text;
break;

case "Email":
filter.EmailAdd ress = txtSearchCriter ia.Text;
break;

default: //LastName
filter.LastName = txtSearchCriter ia.Text;
break;
}

PagedResult<Bus inessLogic.Serv ices.UserProfil epagedResult =
SearchEmployees (filter);
employees =
pagedResult.Res ults.ToList<Bus inessLogic.Serv ices.UserProfil e>();
BindGrid(employ ees.ToList<Busi nessLogic.Servi ces.UserProfile >());
}
}
catch (ThreadAbortExc eption) { }
catch (Exception ex) { ExceptionHelper .Publish(ex); }
}
Sep 19 '08 #4
So, it seems that I do not need to cast my Session object to an IQueryable
object then...since that line does not work anyway. I can just cast it to a
list<>, then put the results of the where into an IQueryable object at that
time. Is that correct?

"bruce barker" wrote:
the where clause in a Linq query does not set a property, its a method
(actually an extension method) that returns another IQueryable object that
the Select method (which also return an IQueryable) can be called on. your
code is throwing away the results of the Where.


-- bruce (sqlwork.com)
"Mike Collins" wrote:
I am trying to set up a dynamic search using linq. I believe the syntax is
correct, but cannot confirm it because when I try to cast my
Session[“Employees”] from a List<to IQueryable<>, I get a cast error
“Unable to cast object of type System.Collecti ons.Generic.Lis t to type
System.Linq.IQu eryable”. Is there a way to cast List<to IQueryable<>, or is
there a different way I need to be doing this?

protected void btnSearch_Click (object sender, EventArgs e)
{
try
{
if (Session["Employees"] != null)
{
IQueryable<Busi nessLogic.Servi ces.UserProfile employees =
(IQueryable<Bus inessLogic.Serv ices.UserProfil e>)(List<Busine ssLogic.Service s.UserProfile>) Session["Employees"];

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
employees.Where (c =c.Username ==
txtSearchCriter ia.Text);
break;

case "Email":
employees.Where (c =c.EmailAddress ==
txtSearchCriter ia.Text);
break;

default: //LastName
employees.Where (c =c.Person.LastN ame ==
txtSearchCriter ia.Text);
break;
}

BindGrid(employ ees.Select(c =>
c).ToList<Busin essLogic.Servic es.UserProfile> ());
}
else
{
List<BusinessLo gic.Services.Us erProfileemploy ees = null;
Shared.Business Logic.UserSearc hFilter filter = new
UserSearchFilte r();

switch (ddSearchCriter ia.SelectedValu e)
{
case "UserName":
filter.Username = txtSearchCriter ia.Text;
break;

case "Email":
filter.EmailAdd ress = txtSearchCriter ia.Text;
break;

default: //LastName
filter.LastName = txtSearchCriter ia.Text;
break;
}

PagedResult<Bus inessLogic.Serv ices.UserProfil epagedResult =
SearchEmployees (filter);
employees =
pagedResult.Res ults.ToList<Bus inessLogic.Serv ices.UserProfil e>();
BindGrid(employ ees.ToList<Busi nessLogic.Servi ces.UserProfile >());
}
}
catch (ThreadAbortExc eption) { }
catch (Exception ex) { ExceptionHelper .Publish(ex); }
}
Sep 19 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1756
by: topmind | last post by:
I am generally new to dot.net, coming from "scriptish" web languages such as ColdFusion and Php. I have a few questions if you don't mind. First, how does one go about inserting dynamic SQL during run-time without lots of quotes? For example, adding "AND" clauses that may or may not be present based on the query criteria form. Some of the asp.net examples use the one-line append approach which
7
3029
by: Ronald S. Cook | last post by:
I've always been taught that stored procedures are better than writing SQL in client code for a number of reasons: - runs faster as is compiled and lives on the database server - is the more proper tier to put it since is a data function But then I've heard that writing SQL in my client .NET code might run just as fast? Dynamic SQL or something? And then there's LINQ on the horizon. Is it a successor to everything
28
16431
by: Marc Gravell | last post by:
In Linq, you can apparently get a meaningful body from and expression's .ToString(); random question - does anybody know if linq also includes a parser? It just seemed it might be a handy way to write a safe but easy implementation (i.e. no codedom) for an IBindingListView.Filter (by compiling to a Predicate<T>). Anybody know if this is possible at all? Marc
15
10873
by: EDBrian | last post by:
My problem is this. Our clients create different fields they want to collect and we allow them build dynamic filters, reports etc... We run some TSQL to actually create the column and all works very well. We are now adding a lot more functionality to our filters and could really benefit from using the LINQ to SQL. I have experimented with the Dynamic Linq...
1
3753
by: john | last post by:
I'm trying to build a LINQ expression that will use a dynamic construction of a LIKE statement in the WHERE clause, it would look something like this in SQL: WHERE TaskGroup Like "*00*" OR TaskGroup Like "*20*" It would be many variations on the above.
2
4812
by: Joey | last post by:
I am querying a DataSet with LINQ. I am running into a problem when trying to construct my query because in the "from" clause I do not know the table name (range variable) until runtime. Possible table names might include "SomeTable1" or "SomeTable236" etc... Unfortunately when I try to use something like "from SomeTable + MyChangingNumber.ToString() in..." in my from clause it does not work. How can I set this up to use a range variable...
4
1451
by: Jon Skeet [C# MVP] | last post by:
On Jul 15, 4:01pm, raulavi <raul...@discussions.microsoft.comwrote: Are you talking about LINQ to Objects or LINQ to SQL? For the latter, I'd say it contains two implicit joins - one in the fact that you've got two "from" clauses and one in o.Product.ProductName. For LINQ to Objects there's a call to SelectMany which is similar to a join in some cases. What are you actually uncertain about, exactly?
2
1403
by: =?Utf-8?B?Tmljaw==?= | last post by:
Hello, I need some assistance with a LINQ query. I've got a simple query: var q = from t in db.Table1 select t; Based on user input I'm adding some where clauses: if (condition1) q = q.Where(t =t.Field1==1);
0
5018
by: Jay Douglas | last post by:
Hello, I've found some posts on creating dynamic WHERE clauses in LINQ to SQL using predicate builders and extending lamda expressions. One issue with these posts is all the examples only use a single customer table. I'm need a way to dynamically create a where clause using multiple tables. None of the tables I'm using have references in the LINQ designer so the JOIN operator is required. If I were to hard type out the query in...
0
10575
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10076
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7616
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.