tags:

views:

67

answers:

3
+2  Q: 

Linq Merge Queries

I have two queries that I would like to merge. This might be a left outer join, but it seems different.

The first query selects distinct stuff from a table:

var d = from d in db.Data
        select (d.ID, d.Label, Value = 0).Distinct;

Lets suppose this returns the following:

{1,"Apple",0}
{2,"Banana",0}
{3,"Cabbage",0}

I then have another query that makes a different selection:

var s = from d in db.Data
        where d.Label != "Apple"
        select (d.ID, d.Label, d.Value);

This returns:

{2,"Banana",34}
{3,"Cabbage",17}

I then want a third query that joins the d and s together based upon their ID and their Label. I want the result to look like this:

{1,"Apple",0}
{2,"Banana",34}
{3,"Cabbage",17}

I'm basically just updating the numbers in the third query, but I have no idea how I should be doing this. It feels like it should be a simple join, but I just cannot get it to work.

A: 

Could you just do

var s = from d in db.Data
        select new
        {
           Id = d.ID,
           Label = d.Label,
           Value = (d.Label == "Apple" ? 0 : d.Value)
        };
Graham Clark
+1  A: 

This should work:

var query1 = from d in db.Data
             select new { d.ID, d.Label, Value = 0 }.Distinct();
var query2 = from d in db.Data
             where d.Label != "Apple"
             select new { d.ID, d.Label, d.Value };

var result =
        from d1 in query1
        join d2 in query2 on new { d1.ID, d1.Label } equals new { d2.ID, d2.Label } into j
        from d2 in j.DefaultIfEmpty()
        select new
        {
            d1.ID,
            d1.Label, 
            Value = d2 != null ? d2.Value : d1.Value
        };

Note: are you sure you want to join on the ID and the label ? It seems rather strange to me... the label shouldn't be part of the key, so it should always be the same for a given ID

Thomas Levesque
+1  A: 

Here is one using method chain, which is my personal favorite.

        var one = db.Data.Select(f => new {f.Id, f.Label, Value = 0});
        var two = db.Data.Select(f => f).Where(f => f.Label != "Apple");

        var three = one.Join(two, c => c.Id, p => p.Id, (c, p) => new {c.Id, c.Label, p.Value});
danijels
whoah, lambda overflow. nice.
RPM1984