我有2個列表,我需要合併來自A和B的連接值,但也包括來自A和B的與連接不匹配的值。Linq查詢合併2個列表
class TypeA
{
public string Key { get; set; }
public int ValueA { get; set; }
}
class TypeB
{
public string Key { get; set; }
public int ValueB { get; set; }
}
class TypeAB
{
public string Key { get; set; }
public int ValueA { get; set; }
public int ValueB { get; set; }
}
var listA = new List<TypeA>
{
new TypeA { Key = "one", Value = 1 },
new TypeA { Key = "two", Value = 2 },
};
var listB = new List<TypeB>
{
new TypeB { Key = "two", Value = 2 },
new TypeB { Key = "three", Value = 3 },
};
我想這些列表合併等於這個:
var listAB = new List<TypeAB>
{
new TypeAB { Key = "one", ValueA = 1, ValueB = null },
new TypeAB { Key = "two", ValueA = 2, ValueB = 2 },
new TypeAB { Key = "three", ValueA = null, ValueB = 3 },
};
什麼是Linq的語句,將做到這一點?我一直在玩,不能完全到達那裏。我可以通過在A到B和Union上進行左外連接來獲得差不多的空間,但是我會得到重複的相交值。
更新
這裏是我根據喬治的回答是什麼:
var joined =
(from a in listA
join b in listB
on a.Key equals b.Key
into listBJoin
from b in listBJoin.DefaultIfEmpty(new TypeB())
select new TypeAB
{
Key = a.Key,
ValueA = a.ValueA,
ValueB = b.ValueB,
}).Union(
from b in listB
where !listA.Any(d => d.Key == b.Key)
select new TypeAB
{
Key = b.Key,
ValueB = b.ValueB,
}
).ToList();
發佈另一個略微更有趣的響應 – 2009-12-18 20:27:40
一些問題/答案,只是沒有得到他們應得的upvotes。這兩個答案都應該更好。他們至少得到了我的讚揚。 – 2010-03-17 17:49:37