LINQ查询合并 [英] Linq Merge Queries

查看:132
本文介绍了LINQ查询合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个疑问,我想合并。这可能是一个左外连接,但它似乎不同。

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

这将返回:

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

我再想联接d和在他们的ID和label的共同基于第三个查询。我希望结果是这样的:

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.

推荐答案

下面是一个使用的方法链,这是我个人最喜欢的

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

这篇关于LINQ查询合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆