Problem with grid when trying to use groupby in LINQ - c#

When trying to use GROUPBY I get an error saying a field 'date1' is not found on selected resource.
var query = (from a in db.Dates
from b in db.Facts
where a.Count_Key == b.Date_key
select new{
a.Date1,
a.Month,
b.Fact_key
});
var query2 = query.GroupBy(x => x.Month );
Grid1.DataSource = query2;
Grid1.DataBind();
So, when I try to bind with query it works perfectly, but query2 yields the error
field date1 not found on selected datasource.
How can I fix this?

The group by returns columns with different names than the original select.
You can do the following to see it "for educational purpose".
create a new Grid2 and use it with automatic columnmapping. Bind Query2 to this Grid2 and you will see the result.

Because you grouped by month, now you have only month field as a key, and collection of grouped items. If you want more fields on data source you need to use aggregate function on date1 field.
For example like this:
var query2 = (from q in query
group q by q.Month into g
select new
{
Month = g.Key,
Date = g.Select(gg=>gg.Date1).Max //or you can use first here etc.
}).ToList()
hope this helps

Related

How to apply Not In Linq?

I have tow tables - OrderRequisition and Order. I can show all the records from OrderRequisition table using linq query:
var list = (from r in db.OrderRequisition
select new SalesOrderViewModel
{
OrderId = r.OrderId ,
OrderNo = r.OrderNo
}).ToList();
I want to show only those records from OrderRequisition table which are not included in Order table. Any clue
Thanks
Partha
A simple approach that might be efficient enough because your database is able to optimize it:
var list = db.OrderRequisition
.Where(or => !db.Order.Any(o => o.OrderId == or.OrderId))
.ToList();
(skipped the SalesOrderViewModel initialization because not relevant for the question)

SQL Where in to Linq with DataTable

I'm trying to achieve this in c#
Select a.Name,a.Param
from Customization a
where a.name in (select Name from Standard)
I have try something like this but it still doesn't work.
merge = dt1.AsEnumerable()
.Where(r => r.Field<string>("Name")
.Contains(dt2.Rows.Contains("Name")))
.CopyToDataTable();
By using the current way we need to get the name list from the second data-table(dt2) for each row in dt1 so I suggest you get the list of names first and then check whether r.Field<string>("Name") contains in the collection. For this, you can use the following code
var NameCollection = dt2.AsEnumerable().Select(x=> x.Field<string>("Name")).ToList();
merge = dt1.AsEnumerable()
.Where(r => NameCollection.Contains(r.Field<string>("Name")))
.CopyToDataTable();

linq - dynamic group by different functions of date

below my simple sql query
SELECT source, date ,COUNT (*)
FROM query
WHERE source in ('a value')
GROUP BY source, date
it took me a while to understand and implement it in linq notation (also thanks to hints from this site) by finally I did it
var selekt = dt.AsEnumerable();
var alldata = from ad in selekt
where ad["source"].ToString().Equals(this.comboBox1.Text)
group ad by new
{
err = ad["err"],
date = ad["date"]
}into g
orderby g.Key.err ascending, g.Key.channel descending
select new
{
Name = g.Key.err,
Date = g.Key.date,
C = g.Count()
};
It is more or less what I need, it also contains "dynamic" element in where clause.
The last point I can't get it is dynamic group clause.
Depends on values on the form I want to group this query by one of three functions of date: day/week/month. I suppose the most difficult part could be group by week.
Anyway, every hint regarding this topis are welcome

Linq to SQL: Sum with multiple columns select

I want to convert the following SQL code into linq to sql but can't seem to find a way
select holder_name,agent_code,sum(total)
from agent_commission
group by agent_code
Can anyone help me? Am kinda stuck with this for quite a while.
Thanks in advance
UPDATE:
I tried the following
var query = (from p in context.Agent_Commissions
group p by new
{
p.agent_code
}
into s
select new
{
amount = s.Sum(q => q.total),
}
);
How do I select the other two columns? What am I missing?
In fact your SQL query works only when the corresponding relationship between holder_name and agent_code is 1-1, otherwise the Group by agent_code won't work. So your linq query should be like this:
var query = from p in context.Agent_Commissions
group p by p.agent_code into s
select new {
holder_name = s.FirstOrDefault().holder_name,
agent_code = s.Key,
amount = s.Sum(q => q.total)
};
Here is your linq query
from a in ctx.agent_code
group a by a.holder_name, a.code into totals
select { holder_name = a.holder_name,
code = a.code,
total = totals.Sum(t=>t.total)}
Given that you have linq2sql context in ctx variable and it has your table in it.

Can the EXCEPT operator exclude data where a column contains data from an array

Assume there is a string of text values comma-separated, like an array:
var excludelist ="apples,oranges,grapes,pears";
The excludelist values may come from a query to a table in a database.
Assume a query wherein we want to return all rows EXCEPT those rows where the field named Fruit contains any items from the excludelist.
var qry = from s in context.Groceries.Where(s => s.Fruit(here is where we need to exclude the items??) join u in context.Users on s.Owner equals u.User_ID
Can someone provide a sample Link to SQL answer?
Did you try Except?
var qry = from s in context.Groceries.Except(excludelist)...
Link to SQL has CONTAINS (and!CONTAINS)
where !excludelist.Contains(i)
select i;
I solved it this way:
I have a database table with the names of the fruits I wish to exclude and I created a List (IList apparently won't work).
List<string> excludedfruit = context.ExcludedFruit.Select(x => x.ExcludedFruitName).ToList();
Then I used the following Linq to SQL query (partially shown)
var qry = from s in context.Groceries
.Where(s => !excludedfruit.Contains(s.Fruit))

Categories