LINQ: How to rewrite the WHERE clause in query? - asp.net

My simple one keyword query works as follows:
var query = from product in dc.catalog
where product.Name.Contains("table")
select product;
I want to provide more flexibility in the query and get keywords from a textbox which can come from a string like "table red round". Here I want the result to have the records that contains ALL of the 3 words (red, round, table) IN ANY ORDER.
How do I rewrite the WHERE clause to handle this? Thanks.

var a = from product in dc.catalog
where textbox1.Text.Split(' ').All(nam => product.Name.Contains(nam))
select product;

How about this (just noticed you want all):
var query = from product in dc.catalog
where textBox.Text.Split(' ').All(s => product.Name.Contains(s))
select product;

// You can produce these matches using any method (string.Split, e.g.)
// Just make sure that they're an array or a list.
var matches = new[]{"table", "red", "round"};
var query = from product in dc.catalog
where matches.All(m => product.Name.Contains(m))
select product;

Look at the Except function
e.g.
var query = from product in dc.catalog
where !selectedItems.Except(product.Name).Any()
select product;

Related

Entity Framework query to return list with simple filter

Is there a simple way to modify this code to return only records where LocationID matches the id I'm trying to pass as a parameter? Needless to say, this doesn't compile. I thought Entity Framework was meant to make things easier, but I've searched online and can't find an understandable example of how to assign a simple query where a field in a single table/entity matches a number.
public async Task<List<PC>> GetPCsAsync(int id)
{
// Get our data. Don't yet know how to feed the variable to EF/Linq
PCList = await (from p in db.PC
select new PC {p.LocationID = id}).ToListAsync();
return PCList;
}
Thanks.
And also if you want to do it using Query Syntax it would be something like this:
PCList = await (from p in db.PC
where p.LocationID == id
select p).ToListAsync();
Here's a link to understand the differences between Query and Method syntax.
var list = db.PC.Where(x=>x.LocationID == id).ToList();
for async
var listAsync = await db.PC.Where(x=>x.LocationID == id).ToListAsync();
I hope it's help you!

How to make a search function able to search two different type of data/item in one search bar

I have code to search the merchants, but I need it to be able to search using the category/subcategories
I have here is:
Category > as the (Food, Leisure, Services, etc.)
so I'll take Food Category for example
Subcategory > Desserts , Bakery, Coffee, Chinese Cuisine
and under each subcategories was the merchants
Sample:
Category(Food) > Subcat(Coffee) > Merchant(J.Co)
so I would just like to type Coffee and hit enter, and the list of merchants under Subcategory of Coffee should show up...
Any tips and tricks?
Thanks by the way.
var merchantList = [];
function PopulateMerchant() {
merchantList = [];
$.ajax({
type: "GET",
url: "/Merchant/ActiveMerchants",
cache: false,
success: function (data) {
if (data != null) {
for (var a = 0; a <= data.length - 1; a++) {
var name = data[a]["name"];
var merId = data[a]["merchantId"];
var type = {
id: merId,
label: name
};
merchantList.push(type);
}
}
},
error: function (error) {
console.log(error);
}
});
return merchantList;
}
That is going to depend on how you are organising your data on the back end and how you organise your search query on your data.
I'll assume you are using a stored procedure in a SQL database, however the same basis process would probably be workable on other data sources. Obviously I've made some assumptions about how your data is connected, but you can adjust to suit
This works based on having your search term to be used in a LIKE statement, so when you set the #searchTerm parameter you would set it to "%{searchterm}%" (with the % symbols)
CREATE PROCEDURE dbo.DoMerchantSearch
(
#searchTerm nvarchar(50)
)
AS
BEGIN
Select merchant.*
From merchant
inner join subCategory on subcategory.id = merchant.subcategoryId
inner join category on category.id = subcategory.categoryId
Where merchant.enabled = 1
and (merchant.name like #searchTerm
or subCategory.name like #searchTerm
or category.name like #searchTerm)
END
So if your search term was "Coffee", this would create an input parameter of "%Coffee%" and would match any category, sub-category or merchant that had "Coffee" in their name.
Hope that points you in the right direction.
Edit: Did forget to mention that you'd also need to ensure your javascript AJAX call was also passing the search term.

Linq Query Distinct Function do not work with DropdownList

I want to assign Linq Query result to dropdownlist which contain a
Distinct function
My Code:-
var area = de.City_Area_View
.Select(m => new { m.Area_Id, m.Area_Name})
.Distinct()
.ToList();
drpfilter.DataTextField = "Area_Name";
drpfilter.DataValueField = "Area_Id";
drpfilter.DataSource = area;
drpfilter.DataBind();
Problem :- When I write this code then I get Below Error
Error:- The method 'Distinct' is not supported.
I get System.NotSupportedException.
I want to assign a Distinct name of area to the DropDownList
So please help me for this problem.
If your set is small enough (so you don't mind fetching all the values from the database), the simplest thing would be to force the distinct part to be performed locally:
var area = de.City_Area_View
.Select(m => new { m.Area_Id, m.Area_Name})
.AsEnumerable()
.Distinct()
.ToList();
AsEnumerable simply "changes" the expression type to IEnumerable<T> instead of IQueryable<T>, so that the compiler calls Enumerable.Distinct instead of Queryable.Distinct - and Enumerable.Distict will definitely work.

ASP.net Entity Framework DropDownList Source Query not Returning Any Result

When I try the following SQL query, I get the result, I want:
SELECT City FROM Hotel GROUP BY City
But the following Entity Framework query does not returning any result:
string CityKey = CityDropDownList.SelectedValue;
MedicalEntities entity = new MedicalEntities();
CityDropDownList.DataSource = (from p in entity.Hotels
where p.City == CityKey
group p by p.City into g
select new
{
City = g.Key
}).ToList();
I have tried so many variations of that query but no go.
I guess, its pretty straight forward and no extra information is needed. Any help would be appreciated
I don't know why you think you need to use the Group by..
CityDropDownList.DataSource = entity.Hotels.Select(x => new { City = x.City })
.Distinct().ToList();

Divide in a Linq to SQL query

How can I form a Linq to sql Query for this code in SQL, I tried several things. This is my basic code:
List<Movie> movies =
(from item in db.Movies select item).ToList<Movie>();
return movies;
This is what I want as a result.
select (Won/Total) as 'rankPercentage'
from dbo.Filmranking
order by rankPercentage desc
Thanks
var movies =
(from items in db.Movies
select new { RankPercentage = item.Won / item.Total })
.ToList();
At this point, movies will be a List<T> where T is a float or int depending on the underlying SQL type (which I cannot discern from your question). If you really want to project this back as a List<Movie>, you will need to project that as follows but your result is not likely to match your SQL table.
List<OtherMovieType> movies =
(from items in db.Movies
select new OtherMovieType() {
Name = item.Name,
RankPercentage = item.Won / item.Total
})
.ToList();
item.Won / db.Awards.Count
Is count a property? I think it is.
You need something called projection, something like this:
var result = db.Movies
.Select(x => new { title=x.Title, rank = (x.Won/x.Total) })
.OrderBy(x => x.rank);
EDIT Maybe you want the title to identify your records :)

Resources