I have two list of objects(authors1, authors2), notice the authors1 is already sorted by SDATE, what I want to do is add the authors2 items into authors1 keeping same order, notice that all new items added needs to go to the end of each group of items
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" }
};
EXPECTED
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
};
how can I accomplish this functionality?
I was trying with two foreach, and then push the items into a new list, please help
IList<Author> response = new List<Author>();
foreach (var author in authors2.GroupBy(x => x.Book).ToList())
{
foreach (var item in author)
{
CodePudding user response:
You could do something like:
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);
}
}