Adam Right
Adam Right

Reputation: 985

Get linq to return IEnumerable<DataRow> result

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..

Upvotes: 2

Views: 5339

Answers (2)

Gabe
Gabe

Reputation: 86708

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;
});

Upvotes: 2

Brian Mains
Brian Mains

Reputation: 50728

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/

Upvotes: 1

Related Questions