问题
How can I convert following SQL query to LINQ in C#?
I don't need all columns from both tables and the result set should be
IEnumerable<DataRow>
Query:
select
c.level, cl.name, c.quantity
from
dbo.vw_categories c
left join
dbo.vw_categoriesLocalization cl on c.level = cl.level
and cl.language = 'en'
where
c.level like '000%'
and c.level <> '000';
Expected:
IEnumerable<DataRow> result = ????
Thanks in advance..
回答1:
Here's how you would write the query:
var query =
from c in db.vw_categories
join cl in db.vw_categoriesLocalization on c.level equals cl.level into clo
from cl in clo.DefaultIfEmpty()
where (cl == null || cl.language == "en")
&& c.level.StartsWith("000")
&& c.level != "000"
select new
{
c.level,
name = cl == null ? null : cl.name,
c.quantity
}
To convert that to IEnumerable<DataRow>
maybe you could do something like this:
var datarows = query.Select(r => {
var row = dataTable.NewRow();
row["level"] = r.level;
row["name"] = r.name;
row["quantity"] = r.quantity;
return row;
});
回答2:
If using LINQ to SQL:
var ctx = new SomeDataContext();
from c in ctx.vw_categories
join cl in ctx.vw_categoriesLocation
on c.level equals cl.level into g
from clv in g.DefaultIfEmpty()
where (clv == null || clv.language == "en")
&& c.level.Contains("000%")
&& c.level != "000"
select new
{
c.level,
name = (clv != null) ? clv.name : default(string),
quantity = c.quantity
};
More info here: http://codingsense.wordpress.com/2009/03/08/left-join-right-join-using-linq/
来源:https://stackoverflow.com/questions/4503517/get-linq-to-return-ienumerabledatarow-result