I need to perform a cross join on a table columns in my database. I use linq and C# to do this. Here is the code i wrote:
var res = (from item_1 in set1
join item_2 in set_2 on new
{
item_1.columnA,
item_1.columnB,
item_1.columnC,
item_1.columnD,
item_1.columnE,
//etc...
}
equals new
{
item_2.columnA,
item_2.columnB,
item_2.columnC,
item_2.columnD,
item_2.columnE,
//etc...
}
select new { item_1,item_2};
I have an asp.net page where users can choose which columns they would like the cross joins to be performed on. And the query should reflect their choice. Some users would only want 2 of of the columns to be used while other will select 10.
I obviously do not want to repeat this query in some switch statement and include the selected columns. I'm wandering if there is a generic way of doing this. Passing a lambda expression ... I'm just not sure how this should be done.
Any help will highly be appreciated.
Take a look at this blogpost from Scott Gu about Dynamic LinQ.
It not only contains an explanation on the matter, links to downloads and examples are also provided. Hope this helps!
Related
I am having difficulty trying to use LINQ to query a sql database in such a way to group all objects (b) in one table associated with an object (a) in another table into an anonymous type with both (a) and a list of (b)s. Essentially, I have a database with a table of offers, and another table with histories of actions taken related to those offers. What I'd like to be able to do is group them in such a way that I have a list of an anonymous type that contains every offer, and a list of every action taken on that offer, so the signature would be:
List<'a>
where 'a is new { Offer offer, List<OfferHistories> offerHistories}
Here is what I tried initially, which obviously will not work
var query = (from offer in context.Offers
join offerHistory in context.OffersHistories on offer.TransactionId equals offerHistory.TransactionId
group offerHistory by offerHistory.TransactionId into offerHistories
select { offer, offerHistories.ToList() }).ToList();
Normally I wouldn't come to SE with this little information but I have tried many different ways and am at a loss for how to proceed.
Please try to avoid .ToList() calls, only do if really necessary. I have an important question: Do you really need all columns of OffersHistories? Because it is very expensive grouping a full object, try only grouping the necessary columns instead. If you really need all offerHistories for one offer then I'm suggesting to write a sub select (this is also cost more performance):
var query = (from offer in context.Offers
select new { offer, offerHistories = (from offerHistory in context.OffersHistories
where offerHistory.TransactionId == offer.TransactionId
select offerHistory) });
P.s.: it's a good idea to create indexes for foreign key columns, columns that are used in where and group by statements, those are going to make the query faster,
In my web project, user can ask questions and publish articles. I keep the questions in the question table and the articles in the articles table. How can I sort the data of these two tables according to the date of creation between them?
I am using Linq-to-SQL.
Agreed with Lews. More info would be good. What isn't working for you? Have you tried a simple Linq2Sql join? Something like:
var select =
from a in _db.Articles
join q in _db.Questions
on a.CreateDate equals q.CreateDate
select a;
I have a situation that I am currently unsure of how to proceed.
I have two datatables that are populated from a database, I also have a list of column names available that can be used to join these two datatables together. I wish to write a set of LINQ queries that will:
Show rows from both datatables (inner join, used for updating one from another).
Show rows from one datatable that don't exist in the other (one query, left join used for inserts, the other a right join used for deletes).
Now I know how to do this with normal LINQ to objects or datatables, however in this case I need to apply the columns to join on dynamically, and there could be more than one. Looking at the following partial example code:
table1.AsEnumerable()
.Join(table2.AsEnumerable(),
dr1 => dr1.Field<string>("ID"),
dr2 => dr2.Field<string>("ID"),
(dr1, dr2) => new
{
FieldID = dr1.Field<string>("ID"),
CdGroup = dr2.Field<string>("Name")
})
The issues are that I don't know the field type so the .Field<string> parts of the statement can't be applied. Also if their are multiple join columns, then I will need to have multiple join statements.
I have read up on dynamic LINQ and it seems quite promising, however I haven't managed to find any information on dynamic LINQ joins like I am trying to do. I know I could probably get the same results using nested loops or the.Select() method on the datatable, but I am trying to apply LINQ to some of the tougher queries that I require.
Do anyone have any pointers or examples of how I could achieve this, or should I just revert to using a non-LINQ approach?
Thanks very much.
If you are using Entity Framework, you could download the Microsoft Dynamics CRM, and use the pattern answered to this question Is there way to structure a QueryExpression so that you could dynamically handle a unknown number of conditions
There is a construct called QueryExpression from which you can model dynamic queries. See this MSDN article http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.query.queryexpression.aspx
Currently I'm running some code and got some question about this. Below are the code listings of two LINQ to Entites queries.
Code listing A:
IQueryable list =
from tableProject in db.Project
select new {StaffInCharge = (
from tableStaff in db.Staff
where tableStaff.StaffId == tableProject.StaffInChargeId
select tableStaff.StaffName)};
Code listing B:
IQueryable list =
from tableProjectin db.Project
join tableStaff in db.Staff
on tableProject.StaffInChargeId
equal tableStaff.StaffId
select new {StaffInCharge = tableStaff.StaffName};
What I want to figure out is which one will be better and faster if I have to select many column from many others table.
Thanks.
this is the comment from #Tim Schmelter
"The article(actually my SO-Question) relates to LINQ-To-DataSet what is based on LINQ-To-Objects. Linq to SQL or Linq to Entities might be optimized by the DBMS in that way that a where clause has the same performance as a join."
and the link is
Why is LINQ JOIN so much faster than linking with WHERE?
i think it is very useful.
I simply can not get this to work out at all, so any expert help would be very much appreciated.
I'm trying (as the subject suggests) to join 2 datatables on Zip Code, but return a table which grouped this by State and has a SUM() of sales.
Here's the latest version of my troubles:
var results =(
from a in dtList.AsEnumerable()
join b in dtListCoded.AsEnumerable()
on a.Field<string>("ZIP") equals b.Field<string>("zip")
group a by {a.Field<string>("StateCode")} into g
select new {
StateCode = a.Field<string>("StateCode"),
SumSales = b.Sum(b => b.Field<double>("SUMSales"))
});
I can join the 2 tables but its getting the result i need that seems to be the tricky bit. If need be I will just have to do 2 queries, but that just seems a bit backward.
Thanks in advance.
Two queries wouldn't be any slower (they should be brought together into a single SQL query upon execution), and would be a lot more readable, transparent during debugging and reusable. I'd recommend breaking it down.