Where clause against multiple options [duplicate] - c#

This question already has answers here:
What is the linq equivalent to the SQL IN operator
(9 answers)
Closed 8 years ago.
Is there any "IN" keyword available in Linq to entities syntax ? I have a listbox where multiple items are added. I want to search for those items in db. My query looks like this:
var result = context.data_vault
.Where(d => d.STATE == lstStates.SelectedItem.Text).OrderBy(d=>d.dv_id)
.Skip(e.NewPageIndex * GridView1.PageSize)
.Take(GridView1.PageSize)
.ToList();
I want d => d.STATE == lstStates.Items. How to change it?

The code:
string[] arr = listview.Items
.Cast<ListItem>()
.Select(i => i.Text) // or .Value
.ToArray();
db.Where(d => arr.Contains(d.STATE);
should be translated into the query:
... WHERE STATE IN ('your', 'array', 'items')

Try this:
var result = context.data_vault
.Where(d => lstStates.Items.Contains(d.STATE)).OrderBy(d=>d.dv_id)
.Skip(e.NewPageIndex * GridView1.PageSize)
.Take(GridView1.PageSize)
.ToList();
Here,
lstStates is List<string>

You can try .Any() or .Contains() syntax
example something like this:
select d from context.Data
Where ListofIdsFromUI.Any(d.Id)
select d

Related

Using orderby with Select() in lambda expression C# [duplicate]

This question already has answers here:
C# list.Orderby descending
(6 answers)
Closed 19 days ago.
I have a variable which have 4 properties. How can I order this by Ids and then using this order for selecting ProductIds.
var products = await _festivalService.GetFestivalProductByProductIds(
searchProductIds, searchModel.FestivalId);
var productIds = products.Select(x => x.ProductId).ToArray();
productIds Should be sorted descending base on Ids and then select productIds.
what about OrderByDescending befor Select?
var productIds = products.OrderByDescending(x => x.ProductId)
.Select(x => x.ProductId).ToArray();

SQL Like clause in LINQ [duplicate]

This question already has answers here:
Like Operator in Entity Framework?
(9 answers)
Closed 1 year ago.
I am trying to migrate a SQL Server stored procedure to LINQ and I am having difficulties when I have a list of partial matches that I need to find in the main table.
In short I need to replicate the following SQL into a LINQ. Any help would be much appreciated.
SQL
DECLARE #filters TABLE([filter] NVARCHAR(20))
INSERT INTO #filters VALUES ('Den%');
INSERT INTO #filters VALUES ('%zil');
INSERT INTO #filters VALUES ('%la%');
SELECT c.*
FROM [Northwind].[dbo].[Customers] c
INNER JOIN #filters f ON c.Country LIKE (f.filter)
ORDER BY Country
C#
var filters = new string[] { "Den*", "*zil", "*la*" };
var results = from C in ctx.Customers
join f in filters c.Country like f
Select new
{
c.CustomerId,
c.Country
};
var result = context.Customers.AsNoTracking()
.Include(x => x.Country)
.Where(x => x.Country.Contains("la") || x.Country.Startwith("Den") || x.Country.EndWith("zil"))
You can use EF.Functions.Like() method provided in EF Core.
We use % for LIKE in strings and not *.
So your query would look like:
var filters = new string[] { "Den%", "%zil", "%la%" };
var result = context.Customers.AsNoTracking()
.Where(c => filters.Any(f => EF.Functions.Like(c.Country, f)))
.OrderBy(c => c.Country)
.ToList();
If you just have one filter then your query would simplify to:-
var filter = "%la%";
var result = context.Customers.AsNoTracking()
.Where(c => EF.Functions.Like(c.Country, filter))
.OrderBy(c => c.Country)
.ToList();
Yo could use the following example:
var result = context.Customers.AsNoTracking()
.Include(x => x.Country)
.Where(x => x.Country.Contains("Den"));
as this example:
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=net-5.0

LINQ Contains() alternatives [duplicate]

This question already has answers here:
Scalable Contains method for LINQ against a SQL backend
(5 answers)
Closed 3 years ago.
I have a list of int and I need to select all record from my query where the id is contained in the second list as showed below:
//my list of ids
var ids=[myquery].select(x=> x.id)
query = query.Where(x => ids.Contains(x.Id));
Now LINQ will convert the above in :
SELECT *
FROM [MyTable]
WHERE ([x].[id] IN (108,687, 689, 691, 694, 705, 703,.....)
Now the ids list will grow a lot and I guess this will ruin the performances.
What would be a better solution considering the the ids list will contain more than 200K item ?
It depends on your model, but you should probably use a navigation property.
Given that you currently have something like this:
var ids =
context
.Entity1
.Where(x => x.Property == value)
.Select(x => x.ID)
.ToHashSet();
var items =
context
.Entity2
.Where(x => ids.Contains(x.ID))
.ToList();
write something like this instead:
var items =
context
.Entity2
.Where(x => x.Entity1.Property == value)
.ToList();
You may need to add such an association to your model before this will be possible.
I would suggest to create a stored procedure as:
there is no unnecessary calls between C# and database(e.g., you are collecting these 200K ids)
less code in C#. So your code will be cleaner and clearer
performance is better as sometimes EF generates inefficient SQL code
So calling stored procedure would look like this:
var user = "johndoe";
var blogs = context.Blogs
.FromSqlRaw("EXECUTE dbo.GetMostPopularBlogsForUser {0}", user)
.ToList();
OR try to use NOT IN operator if items are less 200K:
query = query.Where(x => !ids.Contains(x.Id));
SQL:
SELECT *
FROM [MyTable]
WHERE ([x].[id] NOT IN (108,687, 689, 691, 694, 705, 703,.....)

How to combine a query of the LINQ and a list? [duplicate]

This question already has answers here:
Linq version of SQL "IN" statement
(6 answers)
Closed 4 years ago.
[Sorry if it is a duplicate]
I couldn't find properly solution, so I decided to ask a question.
I have an object companies which returns list of elements.
I would like to write a query which will select these all CompanyId which we have in our list. I don't want to select only one record by using FirstOrDefault().
Example:
var companiesSummary = _context.Company
.Where(c => c.CompanyId == companies.Select(cs => cs.ID))
.Include(country => country.Country)
How can I cope with it? Do you have any ideas?
Select the ids of the companies from your in-memory list and then pass that into the query in the where method:
var ids = companies.Select(cs => cs.ID).ToList();
var companiesSummary =
_context.Company
.Where(c => ids.contains(c.ID))
.Include(country => country.Country)
Assuming your companies contains a list of objects with an ID property you want to compare to Company.CompanyId, your query should look like
int[] ids = companies.Select(cs => cs.ID).ToArray();
var companiesSummary = _context.Company
.Where(c => ids.Contains(c.CompanyId))
.Include(company => company.Country);
var matchingCompanies = companies.Where(c => companyIds.Contains(c.Id))
Make companyIds a HashSet<T> for an efficient Contains.

Simplifying Linq to Object result [duplicate]

This question already has an answer here:
linq select items from child collection
(1 answer)
Closed 6 years ago.
I am not sure if the word "Simplifiying" is suitable in this context or not? But, I have a Linq Query lile below :
result.FIRSTOBJECT
.Select(x => x.SECONDOBJECT
.Select(y => y.THIRDOBJECT
.Where(j => j.Key.Contains("Something"))));
And the result object I get is something like above screen-shot.
My Question: Is there a way that I can make this result to NOT be so nested?
So you want to flatten the sequences? Then you can use SelectMany:
var allMathingThirdObjects = result.FIRSTOBJECT
.SelectMany(x => x.SECONDOBJECT.SelectMany(y => y.THIRDOBJECT))
.Where(j => j.Key.Contains("Something"));
You can loop the result in a foreach or create a collection(f.e. with allMathingThirdObjects.ToList()) or select the first one:
var firstMatchingThird = allMathingThirdObjects.FirstOrDefault(); // null if no match
or select the Key property into a single string:
string allMatchingThirdKeys = String.Join(", ", allMathingThirdObjects.Select(j => j.Key));
Use SelectMany instead
result = result.FIRSTOBJECT
.SelectMany(x => x.SECONDOBJECT
.SelectMany(y => y.THIRDOBJECT
.Where(j => j.Key.Contains("Something"))));
var finalresult = result.FirstOrDefault();

Categories