MVC search a LINQ query - c#

I have a very simple query
var query = (from s in db.Stocks
select s).ToList();
and now basically I want to then search that query to see if any of the stock objects names in the query contain "a"
I have this
if(!string.IsNullOrEmpty(searchModel.Name) )
{
query = query.Where(x => x.Name.Contains(searchModel.Name));
}
but I am getting this error
Cannot implicity convert type "system.collections.generic.ienumerable<etc etc> to system.collections.generic.list
How can I search my query result?
Its ok I have the answer
I just need to add .ToList to the end of my query statement like so
if(!string.IsNullOrEmpty(searchModel.Name) )
{
query = query.Where(x => x.Name.Contains(searchModel.Name)).ToList();
}

The reason is because in the first query
var query = (from s in db.Stocks
select s).ToList();
you have fixed the data type of the variable query to be List (toList()) . Now when you query it again with Where it returns IEnumerable and can't be assigned to the type List . You can do it in one line as in below
var query = from s in db.Stocks
where s.contains(searchModel.Name)
select s

try
query = query.Where(x => x.Name.Contains(searchModel.Name)).ToList();

you can re-write the query as following:
var query = (from s in db.Stocks.ToList()
where !string.IsNullOrEmpty(searchModel.Name) ? s.Contains(searchModel.Name) : true
select s).ToList();
the new added line means: if SearchModel.Name is filled then search using it, otherwise do nothing
or you can keep your code as it, but add .ToList() after the table name, or remote .ToList() on the end of your query code which enforce the datatype of result

Related

Check if text contains any string item from list of string c# linq

I am trying to fetch a list of users after filtering by their name.
Query:
string filter="alex, faheem, Cohen";
var filterArr=filter.Split(new []{','},StringSplitOptions.RemoveEmptyEntries).Select(f=>f.Trim()).ToList();
var users= (from u in DbContext.Users
where filterArr.Any(y=> u.Name.Contains(y)) select u);
This gives me the error:
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
I can't use filterArr.Contains(x.Name) because Name column contains both first name and second name. Just Like in list above their is an item "alex" and I have a name "Alex Hales" combined in Name column. So If I use filterArr.Contains(x.Name) it will not give me the result.
Any help will be much appreciated.
I'm not sure this is possible in a single statement like this. It's too complicated for the poor parsing stuff to work out.
However, you can get an IQueryable(), then iterate over your filters append these as individual WHERE clauses, then these should get added to the SQL properly later.
Something like this:
//this just gets a reference the DbSet, which implements IQueryable<User>
var queryable = _dbContext.Users;
//iterate over the filters and add each as a separate WHERE clause
foreach(var f in filters)
{
//this just adds to the existing expression tree..
queryable = queryable.Where(u=>u.Name.Contains(f));
}
//this will actually hit the database.
var results = queryable.ToList();
This should generate something like this in SQL (entirely pseudo-code)
select
u.*
from
users u
where
(u.username like "%Sue%")
or (u.username like "%Bob%")
Hope this helps...
I think you can do something like this
string filter = "alex, faheem, Cohen";
var filterArr = filter.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(f => f.Trim()).ToList();
var users = _dbContext.Users.Where(x => filterArr.Any(n => n.Contains(x.Name))).ToList();
UPDATE
For your requirement following query will work fine.
string filter = "Alex, faheem, Cohen";
var filterArr = filter.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(f => f.Trim())
.ToList();
var users = _dbContext.Users
.Where(x => filterArr.Any(n => x.UserName.Contains(n))).ToList();
If user has searched for "alex" and in Name (database column) there is "Alex Hales". users query will return the user "Alex Hales".

A query body must end with a select clause or a group clause in a Linq query using lambda expressions

I have this here Linq query using lambda expressions and its throwing an error
A query body must end with a select clause or a group clause
Here is the query in question
var query = from county in HWC.StateCounties.Where(w => w.StateID == id).Select(s => new CountyList
{
CountyID = s.StateCountyID,
CountyName = s.CountyName
});
I even tried adding a .Tolist() at the end and got the same error.
Why is this happening when I clearly have a select clause?
I made a mistake in my query, the query should be this instead
var query = HWC.StateCounties.Where(w => w.StateID == id).Select(s => new
{
s.StateCountyID,
s.CountyName
});
Although it is possible to combine Linq and extensions methods, a Linq query always needs to end with select in c# (In vb this is not necessary).
Maybe it is a matter of taste, but I prefer Linq over extension methods because it makes the code far more readable because all braces are removed.
Your query will look like
var query =
from county in HWC.StateCounties
where county.stateID == id
select new
{
county.StateCountyID,
county.CountyName,
};
If you want to combine the query will look like:
var query =
from county in HWC.StateCounties.Where(s => s.stateID == id)
select new
{
county.StateCountyID,
county.CountyName,
};

how to use session variable in Linq

How to get Session["UserId"] value in Linq Query
var result = (from c in db.UserMaster
where c.UserID == Session["vUSerID"].ToString()
select C ).ToList();
but when i execute it gives me error as follows
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Please guide me how to works with ToString()
You need to materialize the value before you send it off to be translated to SQL:
var userId = Session["vUSerID"].ToString();
var result = (from c in db.UserMaster
where c.UserID == userId
select C ).ToList();
Alternatively, you could try bringing entity into memory first, and then apply the condition to get the filtered result, although not recommended because of the potential performance issue.
var result = db.UserMaster.Select(x => x).ToList().Where(x => x.UserId == Session["vUSerID"].ToString()).ToList();

How to do a LINQ query with Split operation

I have the following linq query:
MyClass myobj = (from p in Session.All<MyClass>()
where p.tags.Split(' ').Contains(searchTag)
select p).FirstOrDefault();
When I run this, I get:
System.NotSupportedException: LINQ to Entities does not recognize the
method 'System.String[] Split(Char[])' method, and this method cannot
be translated into a store expression.
What is a good way to do what I am attempting to do?
The real problem here is the db design, but assuming you have no control over this one idea is to split the query.
First retrieve any rows that contain the search tag anywhere within them.
List<MyClass> myobjs = (from p in Session.All<MyClass>()
where p.tags.Contains(searchTag)
select p).ToList();
Then perform the correct tag search on the retrieved objects in memory.
MyClass myobj = myobjs.FirstOrDefault(m => m.tags.Split(' ').Contains(searchTag));
So, assuming tags = tag1 tag2 tag3, and searchTag is tag2 you can just do:
MyClass myobj = (from p in Session.All<MyClass>()
where p.tags.IndexOf(searchTag) > -1
and searchTag.IndexOf(" ") == -1
select p).FirstOrDefault();

How can i add a condition string to an sql query in an var type

Im working on an source code with an sql query in a VAR type like
var query = select ... from ... where ... ;
is it possible to add an dynamic "where clause" like
string condition = "where x.x > x.y";
e.g. var query = select ... from ... + condition;
Iam sorry for my bad english
You are not clearly stating how your query looks like. Is it a result of a LINQ operation or simply a String?
The keyword var is only usable for design time. The compiler will substitute it with the correct datatype.
If you SQL query is a string, like
var query = "Select ... from ... where ..";
then
string condition = "where x.x > x.y";
query += condition;
is valid because both variables are strings. You can't combine a non string type with a string the way your code suggests.
I do now assume that you are using a LINQ syntax. It is possible to add such conditions to a linq query per code, I think the keywords linq query builder, expression tree and predicate should get you started.
I'd strongly suggest that you stop using the var keyword without exactly knowing what it does and where to use it.
Dynamic Linq exists specifically to solve late-bound scenarios for LINQ:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Allows constructs such as:
NorthwindDataContext northwind = new NorthwindDataContext();
var query = northwind.Products
.Where("CategoryID = 3 AND UnitPrice > 3")
.OrderBy("SupplierID");
If you do not call ToList() and your final mapping to the DTO type, you can add Where clauses as you go, and build the results at the end:
var query = from u in DataContext.Users
where u.Division == strUserDiv
&& u.Age > 18
&& u.Height > strHeightinFeet
select u;
if (useAge)
query = query.Where(u => u.Age > age);
if (useHeight)
query = query.Where(u => u.Height > strHeightinFeet);
// Build the results at the end
var results = query.Select(u => new DTO_UserMaster
{
Prop1 = u.Name,
}).ToList();
This will still only result in a single call to the database, which will be effectively just as efficient as writing the query in one pass.
I saw this answer here by Reed Copsey

Categories