Comparing two datatables through Linq - c#

Hi I'm trying to compare two datatable through Linq. But I get this exception:
Specific cast is invalid
Please help me as I am new to Linq. This is the code I'm using:
var matched1 = from table1 in dtAvailableStores.AsEnumerable()
join table2 in dtControlStores.AsEnumerable()
on table1.Field<int>("STORE_NBR")
equals table2.Field<int>("STORE_NBR")
select table1;
Here STORE_NBR is a string value.

You can have a fairly good idea with this piece of code:
var qry1 = datatable1.AsEnumerable().Select(a => new { MobileNo = a["ID"].ToString() });
var qry2 = datatable2.AsEnumerable().Select(b => new { MobileNo = b["ID"].ToString() });
var exceptAB = qry1.Except(qry2);
DataTable dtMisMatch = (from a in datatable1.AsEnumerable() join ab in exceptAB on a["ID"].ToString() equals ab.MobileNo select a).CopyToDataTable();
References:
Compare two datatable using LINQ Query
Compare two DataTables for differences in C#?

This would happen if that field isn't actually an int.

Related

C# Linq entity query syntax. Return count for So that you can assign to the table

I want to assign an var query value to a (DataGrid)dgEntity without DataTable
How can i do it?
var query = (from c in db.CUSTOMERS.Local
let avg = (from o2 in db.CITIES.Local
join o3 in db.CUSTOMERS.Local on o2.CITNUM equals o3.CITNUM
where (o2.CITY == "Ярославль")
select new { o3.RATING }).Average(t => t.RATING)
where (c.RATING>avg)
select new
{
cusnum = c.CUSNUM
}).Count();
DataTable d = new DataTable();
d.Columns.Add("Count");
d.Rows.Add(new object[] { query });
dgEntity.ItemsSource = d.DefaultView;
Unless I am missing something the result of Count() is getting assigned to query which is just an int and not enumerable. Can you try taking Count() off of the linq query?

C# LINQ list select columns dynamically from a joined dataset

I'm using LINQ to join 2 datatables:
var JoinResult = (from p in WZdt.AsEnumerable()
join t in WZIdt.AsEnumerable()
on p.Field<string>("ID") equals t.Field<string>("ID")
select new
{
p,
t
}).ToList();
WZdt and WZIdt are DataTables. Normally, when wanted to specify columns I would write something like this:
var JoinResult = (from p in WZdt.AsEnumerable()
join t in WZIdt.AsEnumerable()
on p.Field<string>("ID") equals t.Field<string>("ID")
select new
{
FileNo = p.Field<string>("FileNo"),
Title = p.Field<string>("Title"),
M1 = t.Field<int?>("M1"),
RecCount = t.Field<int?>("RecCount")
}).ToList();
But those source datatables are created dynamically based on some logic, so they can differ when it comes to Columns they have. I would like to apply similiar logic to the select part of LINQ, but I don't know how. Can I construct array of columns somehow, like [p.FileNo, p.Title, t.M1, t.RecCount] ?
Or any other way?

Getting The query contains references do Elements defined in the context of other data Error

I'm facing some problem with DataGridView.
I have two LINQ queries:
var query = from x in db.grupyTowarowes
where x.typ == typMoneta
select new
{
x.grupa
};
var test = from z in dbContext.Pick
join g in db.grupyTowarowes on z.Group equals g.grupa
where z.Number == 1000 && g.typ == typMoneta
select new
{
z.Group
};
And then I am setting DataSource:
dataGridView1.DataSource = test;
Query probably works correctly (don't have any errors with query) but I had some error with binding DataGridView, the error which i got is :
The query contains references do Elements defined in the context of other data.
It's weird because when I set:
dataGridView1.DataSource = query;
Then the output is correct.
Because you are using two data contexts in join (db,dbContext), But Linq does not allow join based on multiple contexts!
So you can fetch the records from one source, iterate it to join with another source;
var list1 = dbContext.Pick.ToList();
var list2 = db.grupyTowarowes.ToList();
var test = from z in list1
join g in list2 on z.ID equals g.Id
select new
{
z.A
};
Or materialize your query by using AsEnumerable will fix your issue
:
var test = from z in dbContext.Pick.AsEnumerable()
join g in db.grupyTowarowes.AsEnumerable() on z.Group equals g.grupa
where z.Number == 1000 && g.typ == typMoneta
select new
{
z.Group
};
With AsEnumerable after data is loaded, any further operation is performed using Linq to Objects, on the data already in memory.
Use ToList()
dataGridView1.DataSource = test.ToList();
Problem with your second query is, you are trying to JOIN from two different DB's as pointed below which is not possible. Better, you run each query separately and perform a LINQ - Object join to get the result
from z in dbContext.Pick
join g in db.grupyTowarowes
Try this
dataGridView1.DataSource = new BindingList<String>(test.ToList());

Multiple on clause in LINQ to DataTable Join Query

So I have two DataTables that have the same schema, but different data. I want to join the two tables together where two fields, id3 and print and the same. How would I write this in LINQ?
Right now, this works and gives no compiler errors:
var singOneJoin =
from prod in singOneProd.Table.AsEnumerable()
join agg in singOneAgg.Table.AsEnumerable()
on prod.Field<string>("print") equals agg.Field<string>("print")
select new
{
print = prod.Field<string>("print")
};
But what I really want is this:
var singOneJoin =
from prod in singOneProd.Table.AsEnumerable()
join agg in singOneAgg.Table.AsEnumerable()
on (prod.Field<string>("print") equals agg.Field<string>("print") &&
prod.Field<Int32>("id3") equals agg.Field<Int32><("id3"))
select new
{
print = prod.Field<string>("print")
};
But this gives me compiler errors.
How do I join these two tables together on both the print and the id3 columns?
Regards,
Kyle
Use anonymous objects to join on multiple fields:
var singOneJoin =
from prod in singOneProd.Table.AsEnumerable()
join agg in singOneAgg.Table.AsEnumerable()
on new {
Print = prod.Field<string>("print"),
Id3 = prod.Field<Int32>("id3")
} equals new {
Print = agg.Field<string>("print"),
Id3 = agg.Field<Int32>("id3")
}
select new {
print = prod.Field<string>("print")
};
Keep in mind that anonymous object property names should match.

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.

Categories