I need to do, for example: Select customers whose total Sum of Amount is greater than 0. I tried below code and with reference to this result trying fetch data. but not getting Proper result.
var query = (from a in saleList
group a by a.Cust_Ledger_Entry_No into groups
select groups.Sum( s => s.Amount) > 0).ToList();
I did above query.Now I need data which satisfying above condition.Please help me.
You need a Where
var query = from a in saleList
group a by a.Cust_Ledger_Entry_No into g
where g.Sum( s => s.Amount) > 0
select new { Cust_Ledger_Entry_No = g.Key, SumAmount = g.Sum( s => s.Amount) };
I need result like, customers whose sum of amount greater than 0
with all columns
If a is the customer and you need to select all you can use this query:
var query = from a in saleList
group a by a.Cust_Ledger_Entry_No into g
where g.Sum( s => s.Amount) > 0
from customer in g // flatten each group
select customer;
Related
I currently have 2 lists, one is records, one is for cards. I'm trying to join these two lists on a shared GUID, then group by the name of the card to find the total quantity of cards with that name. I'm just not sure how to get this group by statement to work, does anyone have any ideas?
var values = (from r in records
join c in cards
on r.CardGUID equals c.GUID
orderby c.Name ascending
select new
{
Name = c.Name,
Quantity = r.Quantity
})
.GroupBy(e => new { e.Name });
If you want to calculate the sum of quantities within each group you would add something like this after your groupBy:
.Select(group => new {group.Key, group.Sum(g => g.Quantity)});
I.e. for each group you create a new object, with the key/name and the sum of quantities for that group.
Very new with LINQ here.
I have the following data in my table (TableA):
ID Name SubmissionNo
1 Jim A-1
2 Andy A-2
3 Rick A-2
4 Mary A-3
5 Zim A-4
6 Loren A-1
I then need to create a query which will allow me to get from that table, those records which have duplicate submission numbers.
Here's my solution so far (Context is the database context):
var duplicates = (from tbl in Context.TableA.AsNoTracking()
group tbl by tbl.SubmissionNo into grp
select new { count = grp.Count(), submissionNo = grp.Key})
.Where(x => x.count > 1)
.OrderBy(y => y.submissionNo).ToList();
The variable duplicates then contains the record:
count submissionNo
2 A-1
2 A-2
I then write the main query which will allow me to get all the records from TableA which has duplicate submissionNo
var myList = (from tbl in Context.TableA.AsNoTracking()
join dup in duplicates on tbl.SubmissionNo equals dup.submissionNo
select new
{
ID = tbl.ID,
Name = tbl.Name,
SubmissionNo = tbl.SubmissionNo
})
.ToList();
I am then getting an error for the myList query with
Unable to create a constant value of type 'Anonymous Type'. Only primitive types or enumeration types are supported in this context.
I think there must be a better way to do this as from the TableA above, I practically want the following results:
ID Name SubmissionNo
1 Jim A-1
2 Andy A-2
3 Rick A-2
6 Loren A-1
Your first query, slightly modified, has all information you need:
var myList = from tbl in Context.TableA.AsNoTracking()
group tbl by tbl.SubmissionNo into grp
where grp.Count() > 1
from item in grp
select new
{
count = grp.Count(),
submissionNo = grp.Key,
item.Name,
);
The pattern group into grp - from item in grp is a commonly used query pattern to group items and then flatten the group again, while keeping in touch with the group data (like Count() and Key).
Now you don't need the join anymore and the exception doesn't occur. By the way, the exception tells you that EF can only handle joins with collections of primitive types (int etc.), because it has to translate the whole expression into SQL. There's simply no translation for rich objects like TableA.
By the way, the query can be improved by removing the repeated Count():
var myList = from tbl in Context.TableA.AsNoTracking()
group tbl by tbl.SubmissionNo into grp
let count = grp.Count()
where count > 1
from item in grp
select new
{
count = count,
submissionNo = grp.Key,
item.Name,
);
This will generate a more efficient SQL statement containing one COUNT instead of two.
Since Entity Framework does not support joining in-memory collections of objects with database collections, a common workaround for this is to filter using Contains.
First, you need to get the IDs to filter on:
var duplicates = (from tbl in Context.TableA.AsNoTracking()
group tbl by tbl.SubmissionNo into grp
select new { count = grp.Count(), submissionNo = grp.Key})
.Where(x => x.count > 1)
.OrderBy(y => y.submissionNo)
.ToList();
var duplicateIds = duplicates.Select(x => x.submissionNo).ToList();
And then change your query to perform a WHERE...IN instead of a JOIN:
var myList = (from tbl in Context.TableA.AsNoTracking()
where duplicateIDs.Contains(tbl.SubmissionNo)
select new
{
ID = tbl.ID,
Name = tbl.Name,
SubmissionNo = tbl.SubmissionNo
})
.ToList();
I have the following Linq To Sql queries
var group = "T";
var categoryQuery = from m
in ctx.Material
where m.Group == group
select m;
var maxValue = from c
in categoryQuery
where c.Order == categoryQuery.Select(o => o.Order).Max()
select c.Order;
Where Group is a string value (ex: "T", "S", "R") and Order is an int value. What I want to achieve is to get the highest Order int value from the row in the result set filtered by a particular Group value. Ultimately, I want to use the max value for comparison elsewhere in the code, but I'm having trouble accessing the value from the maxValue IQueryable object.
So a sample from the categoryQuery set would look like this:
Id Group Order
----- ----- -----
100 T 0
101 T 1
102 T 2
103 T 3
So in the second maxValue query, I'd want the 3, because it is the max Order value out of all of the T Group values.
First question: How can I access the int value in maxValue?
Second question: How can I simplify my queries into a single query?
Thank you
It seems to as simple as ordering by Order, descending, and then take the first item:
var group = "T";
var maxValue = (from m
in ctx.Material
where m.Group == group
orderby m.Order descending
select m).FirstOrDefault();
I am trying to write a linq query for one of my dashboard which retrieves data based on some conditions. I want to display records count based on the different status available in my table.
Following is the SQL query in which I am trying to convert into Linq.
select count(id) cnt, 'Available' label from table where date = sysdate
Above query is returning below result in DB IDE. This is the result I want with linq
cnt label
0 Available
I've tried with following linq query but it is returning 0 count and hence result is not being retrieved.
var data = (from a in context
where a.date = System.DateTime.Now
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).ToList();
How do I achieve above mentioned result in linq. Your help will be appreciated.
Thanks
-------------EDIT----------------
Updated LINQ query
var data = (from a in context.TableA
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).Concat(from a in context.TableB
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'WIP'
}).ToList();
To count the number of elements matching a predicate in a linq query simply use the where clause:
var results =
from a in context
where a.date.Date == DateTime.Now.Date
&& a.id == someIdHere
select a;
var data = new {
count = results.Count(),
label = "Available"
};
Or, in extension method syntax (which I prefer):
var results = context.Where(a => a.date.Date == DateTime.Now.Date && a.id == someIdHere);
var data = new {
count = results.Count(),
label = "Available"
};
Also be careful when comparing a DateTime object with regards to what results you desire; comparing DateTime.Now to a date will likley return false since it will compare the time code as well, use the DateTime.Date property to obtain only the date from the object for the purposes of comparison.
Find sum of product of 2 columns in LINQ
I have a list of educationprogram objects with 2 properties NOOfPerson & Hours.
I want a sum of product of 2 properties
SUM[NOOfPersons*Hours]
How can I write a LINQ query for this?
List<educationprogram> edu = (from e in dbContext.educationprograms
where e.YearId == 2015
select e).ToList();
This returns the list of object I have to use. But how can I return SUM[Col1*Col2]?
If the two columns are under the educationprograms table then:
var sum = dbContext.educationprograms.Sum(ep => ep.NoOfPeople * ep.Hours);
you can also add a Where clause:
var sum2 = dbContext.educationprograms.Where(e => e.Year == 2015).Sum(ep => ep.NoOfPeople * ep.Hours);
var edu= from e in dbContext.educationprograms
where e.YearId == 2015
select new
{
sum = e.NoofPersons*e.Hours
}).ToList();
now edu is the list of products of noofperson column and hours column.