簡體   English   中英

加入兩個不同對象的列表並創建一個新列表

[英]Join two lists of different objects and create a new list

我有兩個不同對象的列表。

List<ObjA> objAs = new List<ObjA>();
List<ObjB> objBs = new List<ObjB>();

它們具有以下 class 結構。

public class ObjA
{
    public int Id;
    public int ObjBId;
}

public class ObjB
{
    public int Id;
    public string Title;
}

將 objA 的ObjBId屬性加入到 ObjB 的Id屬性中,我想在 ObjB 的標題旁邊創建一個 ObjA 的 Id 列表。 像這樣的東西:

List<int, string> output = new List<int, string>();
// where int = ObjA's Id, string = ObjB's Title

如何在 LINQ 中做到這一點? 除了使用 Concat 和創建包裝器 class 之外,還有其他選擇嗎?

Enumerable.Join應該可以幫助你。

var result = objAs.Join(objBs,x=>x.ObjBId,y=>y.Id,(x,y)=>new {x.Id,y.Title})
                  .ToList();

您可以使用Join方法並將結果作為命名元組List<(int, string)>的列表返回(從 C# 7 開始可用),因為List<int, string>不是有效的 C# 聲明。

var output = objAs.Join(objBs, a => a.ObjBId, b => b.Id, (a, b) => (a.Id, b.Title)).ToList();

您也可以使用匿名對象代替元組,例如(a, b) => new { a.Id, b.Title}

您可以使用連接並返回列表

var result = (from a in objAs
    join b in objBs on a.ObjBId equals b.Id
    select new
    {
       a.ObjBId,
       b.Title
    }).ToList();

因此,對於 objAs 的每個元素,您都需要獲取 Id,如果 objBs 中存在具有相同 Id 的 object,則需要來自 objA 的 Id 和來自 objB 的標題。

事實上,由於 objA 和 objB 的 Id 是相等的,所以你不管是從 objA 還是從 objB 獲取 Id。

如果 objB 中沒有具有相同 ID 的項目,則您沒有寫出您想要的內容。 假設在這種情況下您想要 null。

var result = objAs.GroupJoin(objBs,  // GroupJoin A with B
    objA => objA.Id,                 // from every element in A take the Id
    objB => objB.Id,                 // from every element in B take the Id

    // ResultSelector: take all elements of A, each with the matching elements from B
    (objA, matchingObjBs) => new
    {
        Id = objA.Id,
        Title = matchingObjBs.Select(objB => objB.Title).FirstOrDefault(),
    });

GroupJoin 的好處在於,您還可以從 A 中獲取沒有匹配 B 的元素。如果 B 中有多個匹配項,則取第一個。

如果您不希望 A 中的項目在 B 中沒有匹配的 Id,則僅從 B 中獲取在 A 中具有 Id 的元素就足夠了:

var idsA = objAs.Select(objA => objA.Id);
var result = objBs.Where(objB => idsA.Contains(objB.Id));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM