我有名為文章的類串列和 int 串列。我喜歡在 LINQ 中執行以下步驟
我的課是
public class Article
{
public string Content { get; set;}
public int CategoryID {get; set;}
}
我的文章清單是
List<Article> articles = new List<Article>()
{
new Article() {Content = "test1", CategoryID = 1 },
new Article() {Content = "test2", CategoryID = 1 },
new Article() {Content = "test3", CategoryID = 1 },
new Article() {Content = "test4", CategoryID = 2 },
new Article() {Content = "test5", CategoryID = 2 },
new Article() {Content = "test6", CategoryID = 3 },
new Article() {Content = "test7", CategoryID = 4 },
new Article() {Content = "test8", CategoryID = 4 },
};
我的 int 清單是
List<int> filteredCategoriesID = new List<int>() {1,2};
我想創建一個包含所選類別串列的文章的新文章串列。
我的代碼是
var newArticleList = articles
.IntersectBy(filteredCategoriesID, a => a.CategoryID)
.ToList();
我預期的結果
NewArticleList =
{
( Content = "test1", CategoryID = 1 ),
( Content = "test2", CategoryID = 1 ),
( Content = "test3", CategoryID = 1 ),
( Content = "test4", CategoryID = 2 ),
( Content = "test5", CategoryID = 2 ),
}
但是 NewArticleList 只有一個文章物件。
uj5u.com熱心網友回復:
您可以嘗試過濾,即全部articles來自初始收藏Where filteredCategoriesID Contains文章的CategoryId:
var newArticleList = articles
.Where(article => filteredCategoriesID.Contains(article.CategoryId))
.ToList();
uj5u.com熱心網友回復:
我建議首先將您的過濾器串列轉換filteredCategoriesID為 a ,因為on的HashSet時間復雜度是for 。所以,你可以做的是:Contains()ListO(N)O(1)HashSet
var filterSet = new HashSet<int>(filteredCategoriesID);
var newArticleList = articles.Where(a => filterSet.Contains(a.CategoryId)).ToList();
uj5u.com熱心網友回復:
使用 LINQ 的另一種方式
var newArticleList = (from a in articles
join cid in filteredCategoriesID on a.CategoryID equals cid
select a)
.ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/497326.html
