加入集合和分配值

时间:2015-05-15 11:11:11

标签: c# linq join collections

我有两个集合,我想根据键属性加入它们,并将一个集合的值分配给其他集合。我是按照以下方式做的

var joinedData =   from collection_one in Office.Employees 
               join collection_two in NewOffice.Employees 
                  on collection_1.OfficeId equals collection_two.OfficeId
               select new { collection_one, collection_two};


// Declare a new Collection 

ICollection<Office.Employees> updatedCollection = New List<Office.Employees>();

// Assign New Collection_Two Values to Collection_One
foreach (var item in joinedData.ToList())
            {
                item.collection_one.Deleted = item.collection_two.Deleted;
                updatedCollection .Add(item.obp);
            }

这不会产生正确的结果。我的Join正在生成比内部联接更多的记录。有谁能发现问题?

1 个答案:

答案 0 :(得分:1)

使用DefaultIfEmpty()尝试左连接:

    var updatedCollection =
        (from collection_one in Office.Employees 
         from collection_two in NewOffice.Employees.Where(x => x.OfficeId == collection_one.OfficeId).DefaultIfEmpty()
         where collection_two == null
         select new { 
             collection_one, 
             collection_two
         }).Select(x => {
            x.collection_one.Deleted = x.collection_two.Deleted;
            return x.obp;
         });

但x.obp是什么?也许结果应该是x.collection_one?