Can you use grouping in Entity Framework [duplicate] - c#

This question already has answers here:
SQL to Entity Framework Count Group-By
(5 answers)
Closed 3 years ago.
I have some SQL code that I want to "convert" to an entity framework 'call'.
This is the code:
select itemStatus, avg(UnitPrice) from ItemSalesHistory
where item = 'BQF09-L-Q007'
group by itemStatus
I'm new to using Entity Framework.

Yes you can. If you take a look at this answer, you can apply it to your situation:
var query = ItemSalesHistory
.Where(x => x.item == 'BQF09-L-Q007')
.GroupBy(x => x.itemStatus)
.Select(g => new { itemStatus = g.Key, avg = g.Average(x => x.UnitPrice) });

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();

How to iterate through list in Where clause in C# .Net [duplicate]

This question already has answers here:
Returning one of each object based on list of Ids and other property using EF/Linq
(3 answers)
Closed 25 days ago.
I have this part of code:
using (var context = _contextFactory.CreateDbContext())
{
return await context
.Xxxx
.SetTracking(false)
.Where(t => t.Id == xxxId)
.Select(t => new ResultsByIdSqlModel(
xxxId,
t.Name,
t.SessionId,...
But I am not sure how to modify this when xxxId is list of Ids as I want to return for each id response.
you would need Contains:
using (var context = _contextFactory.CreateDbContext())
{
return await context
.Xxxx
.SetTracking(false)
.Where(t => xxxIdList.Contains( t.Id ) )
.Select(t => new ResultsByIdSqlModel(
xxxId,
t.Name,
t.SessionId,...
The Contains method will be tranlated into IN in SQL.

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.

Unexpected result in a LINQ to Entities query [duplicate]

This question already has an answer here:
Entity Framework v6 GroupBy Losing Original Ordering
(1 answer)
Closed 6 years ago.
I have following Entities in my DbContext:
I wrote following LINQ to Entities query in LINQPad to find all areas that an order passes(An order passes some areas to produced, an area may repeat):
OrderItems.Include("NominalRoutings.OperationCatalog.WorkCenter.AreaSpecification")
.Where(x=>x.Id == 799730)
.Select(r=>r.NominalRoutings.Where(t => t.OperationCatalog.IsActive)
.Select(t=>new
{
AreaTitle=t.OperationCatalog.WorkCenter.AreaSpecification.Title,
t.ItemSequence
})
.OrderBy(t => t.ItemSequence)
.Select(g => new{g.ItemSequence,g.AreaTitle})
).FirstOrDefault()
And this is its result:
Now, I want to find areas that my Order passed so I changed above query to:
OrderItems.Include("NominalRoutings.OperationCatalog.WorkCenter.AreaSpecification")
.Where(x=>x.Id == 799730)
.Select(r=>r.NominalRoutings.Where(t => t.OperationCatalog.IsActive)
.Select(t=>new
{
AreaTitle=t.OperationCatalog.WorkCenter.AreaSpecification.Title,
t.ItemSequence
})
.OrderBy(t => t.ItemSequence)
.GroupBy(routing => routing.AreaTitle)
.Select(t=>t.Key)
).FirstOrDefault()
The result is:
But I expect following result:
1 Melt
2 LAB
3 PU09
4 LSM
Because I orderd the areas by ItemSequence and then grouped it by Title. Am I mistaken? or there is any problem in my code?
OrderBy returns an IOrderedEnumerable and obviously keeps the order but when using GroupBy it isn't required to keep any order (if it would it would have returned IOrderedEnumerable too to make it clear).
What I suggest you do is first GroupBy and then Order
.Select(t => new { AreaTitle = t.OperationCatalog.WorkCenter.AreaSpecification.Title, t.ItemSequence })
.GroupBy(routing => routing.AreaTitle)
.OrderBy(t => t.Min(x => x.ItemSequence))
.Select(t=>t.Key)

C# Is it possible to check if any specific digit is present in an ID? [duplicate]

This question already has answers here:
Integer Contains Using Linq
(2 answers)
Closed 6 years ago.
I want to have a search option where
1.user will type any letter that matches the name from database table.
This works smoothly.
string userinput = "hel"
List<string> queryResult = _myContext.Products
.Where(r => r.Name.Contains(userinput))
.Select(r => r.Name)
.ToList();
2. user will type any digit that should match the ID if that digit/digits exist in the ID it should give me a list of those ID
can i do something thing like that??
int queryId= 12;
_myContext.Products.Where(r => r.ID.contains(queryId)).Select(r => r.ID).ToList();
string queryId = "12";
List<string> queryResult = _myContext.Products
.Where(r => r.Id.Tostring().Contains(queryId))
.Select(r => r.ID)
.ToList();

Categories