[英]How to add a new item into an specific position of a list of objects
我有兩個對象列表(authors1,authors2),注意 authors1 已經按 SDATE 排序,我想做的是將 authors2 項目添加到 authors1 中,保持相同的順序,注意添加的所有新項目都需要 go 到末尾每組物品
IList<Author> authors1 = new List<Author>
{
new Author { Book = "c#", Code="A11" , SDate = 1 },
new Author { Book = "c#", Code="A22" , SDate = 1 },
new Author { Book = "c#", Code="A31" , SDate = 1 },
new Author { Book = "js", Code="B43" , SDate = 2 },
new Author { Book = "js", Code="B33" , SDate = 2 },
new Author { Book = "js", Code="B41" , SDate = 2 },
new Author { Book = "java", Code="C27", SDate = 3 },
new Author { Book = "java", Code="C33", SDate = 3 },
new Author { Book = "java", Code="C78", SDate = 3 }
};
IList<Author> authors2 = new List<Author>
{
new Author { Book = "c#", Code = "A21" },
new Author { Book = "java", Code = "C23" }
};
預期的
IList<Author> authors1 = new List<Author>
{
new Author { Book = "c#", Code="A11", SDate = 1 },
new Author { Book = "c#", Code="A22", SDate = 1 },
new Author { Book = "c#", Code="A31", SDate = 1 },
new Author { Book = "c#", Code="A21", SDATE = 1 }, // new item added to the end of this group
new Author { Book = "js", Code="B43", SDate = 2 },
new Author { Book = "js", Code="B33", SDate = 2 },
new Author { Book = "js", Code="B41", SDate = 2 },
new Author { Book="java", Code="C27", SDate=3 },
new Author { Book="java", Code="C33", SDate=3 },
new Author { Book="java", Code="C78", SDate=3 },
new Author { Book="java", Code="C23", SDATE=3 } // new item added to the end of this group
};
我怎樣才能完成這個功能?
我正在嘗試使用兩個 foreach,然后將這些項目推送到一個新列表中,請幫忙
IList<Author> response = new List<Author>();
foreach (var author in authors2.GroupBy(x => x.Book).ToList())
{
foreach (var item in author)
{
你可以這樣做:
foreach(Author a in authors2)
{
Author b = authors1.Where(x => x.Book == a.Book).LastOrDefault();
if (b != null)
{
int index = authors1.IndexOf(b);
a.SDate = b.SDate;
authors1.Insert(index + 1, a);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.