Get linq to return IEnumerable<DataRow> result

这一生的挚爱 提交于 2020-01-04 09:03:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!