.net 使用linq合并对象列表,同时在一个列表中显示对条件的偏好

.net 使用linq合并对象列表,同时在一个列表中显示对条件的偏好,.net,linq,c#-4.0,list-manipulation,.net,Linq,C# 4.0,List Manipulation,我有一个名为Content的类,它包含一些属性 属性之一是CultureCode 列表A包含所有“en”内容类 列表B包含所有“en GB”内容类 我想合并它们,以便:我们只得到最终列表中的“en”内容,但只要在en GB中有匹配项,就需要将该项包含在最终列表中而不是en中 因此,如果: 列举 名单B 然后 混合名单 我试过这样的方法: IEnumerable<Content> mixed = from x in listA join y in listB on new {x.Pro

我有一个名为Content的类,它包含一些属性

属性之一是CultureCode

列表A包含所有“en”内容类 列表B包含所有“en GB”内容类

我想合并它们,以便:我们只得到最终列表中的“en”内容,但只要在en GB中有匹配项,就需要将该项包含在最终列表中而不是en中

因此,如果:

列举 名单B 然后

混合名单 我试过这样的方法:

IEnumerable<Content> mixed = from x in listA
join y in listB on new {x.Property1, x.Property2, x.Property3} equals
    new {y.Property1, y.Property2, y.Property3} into g
from o in g.DefaultIfEmpty(new Content()
{
    Id = x.Id,
    CultureCode = x.CultureCode,
    Property1 = x.Property1,...
})
where
(
    ...
)
select new Content()
{
    Id = o.Id,
    CultureCode = o.CultureCode,
    Property1 = o.Property1,
    Property2 = o.Property2,
    Property3 = o.Property3,
};
IEnumerable mixed=来自列表A中的x
在新的{x.Property1,x.Property2,x.Property3}上的列表B中加入y
将{y.Property1,y.Property2,y.Property3}新添加到g中
从g.DefaultIfEmpty中的o开始(新内容()
{
Id=x.Id,
CultureCode=x.CultureCode,
Property1=x。Property1,。。。
})
哪里
(
...
)
选择新内容()
{
内径=外径,
CultureCode=o.CultureCode,
属性1=o.属性1,
Property2=o.Property2,
属性3=o.属性3,
};
这有多种变化,但结果永远不会完全正确


有什么想法吗?

类似这样的想法就可以了:

var result = (from a in listA
              join b in listB on a.Property1 equals b.Property1 into g
              from j in g.DefaultIfEmpty()
              select new Content() { 
                   // Favour listA's culture code
                   CultureCode = j == null ? a.CultureCode : j.CultureCode, 
                   Property1 = a.Property1 
              });

还有一个活生生的例子来演示:

现在就试试这个。看起来很有希望:)var结果包含“对象引用未设置为对象的实例”。请查看它的工作实例-您在自己的代码中做了一些错误没有问题。很乐意帮忙。
en - 1
en-GB - 2
en - 3
en-GB - 4
en - 5
IEnumerable<Content> mixed = from x in listA
join y in listB on new {x.Property1, x.Property2, x.Property3} equals
    new {y.Property1, y.Property2, y.Property3} into g
from o in g.DefaultIfEmpty(new Content()
{
    Id = x.Id,
    CultureCode = x.CultureCode,
    Property1 = x.Property1,...
})
where
(
    ...
)
select new Content()
{
    Id = o.Id,
    CultureCode = o.CultureCode,
    Property1 = o.Property1,
    Property2 = o.Property2,
    Property3 = o.Property3,
};
var result = (from a in listA
              join b in listB on a.Property1 equals b.Property1 into g
              from j in g.DefaultIfEmpty()
              select new Content() { 
                   // Favour listA's culture code
                   CultureCode = j == null ? a.CultureCode : j.CultureCode, 
                   Property1 = a.Property1 
              });