[英]Union/Merge 2 lists of different type and return a list of one type with LINQ
[英]C# LINQ Intersect 2 Different Type Lists and Return one Type
我正在嘗試在 2 個列表中查找公共行,如下所示:
public class ListA
{
public string Id { get; set; }
public string Name { get; set; }
}
List<ListA> listA = new List<ListA>();
List<string> listB = new List<string>();
List<ListA> intersect = listA.Where(x => listB.Any(y => y == x.Id)).ToList();
所以上面的 Linq 查詢將根據 Id 屬性獲取 2 個列表中的所有常見項目,我如何使用 Intersect/IntersectBy Id 做同樣的事情並返回 ListA 的類型?
使用IntersectBy
LINQ 方法。 這將使您可以將每個 ListA 條目的 Id 屬性與與提取的屬性類型相同的另一個列表進行比較。
IEnumerable<ListA> intersect = listA.IntersectBy(listB, a => a.Id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.