How to convert MySQL Group By to C# LINQ Query? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have the following code in MySQL
SELECT Query,SUM(TotalResults)
FROM TotalJobResults
GROUP BY Query
ORDER BY `SUM(TotalResults)` DESC
I am trying to duplicate this function calling a MongoDB Collection in C# and cannot seem to actually understand it very well. I have the code below but it seems far from answering the problem,
var t = from q in _jobCollection.Find(_ => true).ToList().GroupBy(
p => p.Query,
p => p.TotalResults,
(key, g) => new { Query = key, Total = g.ToList().Sum() }
);
Thanks for any light you can shed on this!

Looks like it works if I put a select q on the end. hmm! my error
var t = from q in _jobCollection.Find(_ => true).ToList().GroupBy(
p => p.Query,
p => p.TotalResults,
(key, g) => new { Query = key, Total = g.ToList().Sum() }
) select q;

Related

how to use joining with LinQ To Entity [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have this code
var value = (from dc in _context.ContractDetails
where dc.EmployeeID == id
select dc.Amount);
return value;
}
is it acceptable to do Value.Sum();
You want to return the sum it looks like. Instead of having query be a decimal, just let it be what it wants (var, it's really IEnumerable<decimal>). Then you can return an aggregate on that. Sum for example
var query = from emp in Employees
join cd in ContractDetails
on emp.EmployeeID equals cd.EmployeeID
where cd.EmployeeID == id
select cd.Amount;
return query.Sum();
If this is all it does, then I also feel like you don't need to join at all, and it would be simpler to do
var query = from cd in ContractDetails
where cd.EmployeeID == id
select cd.Amount;
return query.Sum();
... unless you were using the join to test for the existence of an employee in the Employee table as a condition.
Your linq statement results in an IQueryable<Amount>, you would need to take that result and call Sum() on it to get the result you're seeking.
First, isn't there a navigation property you can use (i.e. Employee.ContracteDetails) instead of manually joining the two sets? For example,
var sum = _context.Employee
.Where( e => e.Id == id )
.Select( e => e.ContractDetails.Sum( cd => cd.Amount ) )
.SingleOrDefault();
Second, you're not using any information you need from Employee, even your where clause references ContractDetails alone; why start your query there? Work with _context.ContractDetails instead:
var sum = _context.ContractDetails
.Where( cd => cd.EmployeeId == id )
.Sum( cd => cd.Amount );

how to write a nested Sql query in Linq [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
so i have this query in sql:
select (select ConfigItemDescripcion from SGRC_ConfigItem where ConfigId = 'SEGM' and ConfigItemId = SegmentoId) Segmento,
(select ConfigItemDescripcion from SGRC_ConfigItem where ConfigId = 'MRCA' and ConfigItemId = MarcaId) Marca,
Producto,
Familia
from sgrc_emisor
where EmisorCuenta = '3702406435'
I want to write the same query in a linq expression or a lambda expression.
Thanks for the help in advance
Finally i manage to come up with the query in linq, dont know how to do it in lambda, but it works fine.
var obj = (from emisor in _context.DbSetEmisores
where emisor.EmisorCuenta == cuenta
select new EmisorDto
{
Segmento =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "SEGM" && itemConf.ConfigItemID == emisor.SegmentoId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Marca =
((from itemConf in _context.ItemsDeConfiguracion
where itemConf.ConfigID == "MRCA" && itemConf.ConfigItemID == emisor.MarcaId
select new { itemConf.ConfigItemDescripcion }).FirstOrDefault().ConfigItemDescripcion),
Producto = emisor.Producto,
Familia = emisor.Familia,
SegmentoId = emisor.SegmentoId,
MarcaId = emisor.MarcaId,
}).FirstOrDefault();
When using LINQ you can use either Query syntax as shown in the LINQ below (If you are familiar with SQL then this looks more natural).
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq
The other option is to use Method syntax, and below is a short example. This allows for chaining of methods, biggest thing to keep in mind is "var" should be used, the return type is dynamic and the compiler will help you out a lot if you just use "var"
var items = _list.Where(x => x.Attribute1 == "NextField")
.Where(x => x.Attribute2 == "Something else");
Other things that hangs folks up sometimes is LINQ uses "delayed execution"

Query with case statement from SQL Server to Linq query c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have the following query in sql server
select COUNT(mc_owner) as nbr ,
case mc_owner when 'Element1' then 'Element1' else 'others' end Owner
from [dbo].[full]
where (date_reception > '01-01-2015')
group by (CASE mc_owner WHEN 'Element1' THEN 'Element1' ELSE 'others' END)
order by nbr desc
I need to convert it to entityframework linq query
Try this,
var result = fulltableData.Where(x=>x.date_reception > '01-01-2015')
.GroupBy(x=> x.mc_owner.Equals("Element1")?"Element1":"others")
.Select(x=> new{ nbr = x.Count(), Owner = x.Key})
.OrderByDescending(x=>x.nbr);
I understand you want to select the number of occurrences of a certain mc_owner compared to all others. The following LINQ query should produce the same result:
full.Where(f => f.date_reception > new DateTime(2015, 1, 1))
.GroupBy(f => f.mc_owner == "Element1" ? f.mc_owner : "others")
.OrderByDescending(group => group.Count())
.Select(group => new { Owner = group.key, nbr = group.Count());

linq convert query syntax to method syntax [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I convert this query syntax to method syntax in linq:
return (from x in db.Table1
join y in db.Table1 on x.ID equals y.ID - 1
where Convert.ToInt32(y.ID) >= Convert.ToInt32(x.ID)
orderby x.Name
select x).Distinct();
Which approach is better? I like this query approach better but I was asked to work with method syntax which looks too bloated to me.
var results = db.Table1.Join
(
db.Table1,
x=>x.ID,
x=>x.ID - 1,
(x,y)=>new{OuterTable = x, xid = x.ID, yid = y.ID}
)
.Where(x=>Convert.ToInt32(x.yid ) >= Convert.ToInt32(x.xid))
.Select(x=>x.OuterTable)
.OrderBy(x=>x.Name)
.Distinct();

How to search keywords using "And" clause in database : LINQToSQL [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I developed a search functionality recently which searches database on EnglishValue column in Tag table. I recieve list of Keywords from search box and i search it using following query and it gives me correct results.
List<string> keywords = new List<String>(searchText);
IQueryable<Tag> tags = from p in db.Tags
where keywords.Contains(p.EnglishValue)
select p;
var matchingTagList = tags.ToList();
Now one of the ask is to search using "AND", currently LINQ query is doing OR. If any one can give suggestions how to do AND search using LINQToSQL that will help.
I am adding more details on how my database looks like. If i seach for Pet-Friendly and Wi-Fi than i should get Id= 1.
Try this:
List<string> keywords = new List<String>(searchText);
IQueryable<Tag> tags = from p in db.Tags
where keywords.All(x=> p.EnglishValue.Contains(x))
select p;
var matchingTagList = tags.ToList();
Simply try this. That why I love LINQ. Assuming you keyword is containing the term and also some varialble here called Num =5;
List<string> keywords = new List<String>(searchText);
IQueryable<Tag> tags = from p in db.Tags
where keywords.Contains(p.EnglishValue) && p.num==5
select p;
var matchingTagList = tags.ToList();

Categories

Resources