在LINQ加入两套

时间:2010-05-19 16:41:09

标签: c# linq join set

    var setsA = new List<SetA> {
        new SetA { SsnA = "3450734507", name = "setA"},
        new SetA { SsnA = "6833467788", name = "setA"},
        new SetA { SsnA = "5452347787", name = "setA"},
        new SetA { SsnA = "9345345345", name = "setA"},
    };

    var setsB = new List<SetB> {
        new SetB { SsnB = "5452347787" ,name = "setB"},
        new SetB { SsnB = "9345345345", name = "setB"},
    };

当我使用这个linq时:

var Set =
                from seta in setsA
                join setb in setsB
                 on seta.SsnA
                    equals setb.SsnB
                select new { 
                    SSN = seta.SsnA,
                    NAME = setb.name
                };

我得到这个值:

{ SSN = "5452347787", NAME = "setB" }
{ SSN = "9345345345", NAME = "setB" }

但是我希望将SET结合起来,结果将是:

{ SSN = "3450734507", NAME = "setA" }
{ SSN = "6833467788", NAME = "setA" }
{ SSN = "5452347787", NAME = "setB" }
{ SSN = "9345345345", NAME = "setB" }

这将是一个结果集,告诉我NAME属性的名称,它取自哪个集合,如果在SetA和SetB中找到SSN,它将具有属性NAME =“setB”

有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:4)

似乎你想要一个外连接 - 这是使用GroupJoin完成的:

var set = setsA.GroupJoin(
    setsB,
    sa => sa.SsnA,
    sb => sb.SsnB,
    (a, bs) => new { SSN = a.SsnA, NAME = bs.Any() ? "setB" : "setA" });

答案 1 :(得分:0)

这里描述的LINQ方式: http://msdn.microsoft.com/en-us/library/bb397895.aspx看起来像这样(在函数上与lambda方式相同):

 var set = from a in setsA
           join b in setsB on a.SsnA equals b.SsnB into g
           from o in g.DefaultIfEmpty()
           select new { SSN = a.SsnA, NAME = (o != null ? o.name : a.name)};