I have a below list and i need to remove adjacent duplicate item only.
Sample List
var data = new List<NewsModel>
{
new NewsModel { ID = 1, Name = "AAA" },
new NewsModel { ID = 2, Name = "AAA" },
new NewsModel { ID = 3, Name = "BBB" },
new NewsModel { ID = 4, Name = "CCC" },
new NewsModel { ID = 5, Name = "CCC" },
new NewsModel { ID = 6, Name = "AAA" },
new NewsModel { ID = 7, Name = "DDD" },
new NewsModel { ID = 8, Name = "DDD" },
new NewsModel { ID = 9, Name = "CCC" }
};
Expected Result
var data = new List<NewsModel>
{
new NewsModel { ID = 1, Name = "AAA" },
new NewsModel { ID = 2, Name = "BBB" },
new NewsModel { ID = 3, Name = "CCC" },
new NewsModel { ID = 4, Name = "AAA" },
new NewsModel { ID = 5, Name = "DDD" },
new NewsModel { ID = 6, Name = "CCC" }
};
I have tried it like below,But it’s not came as expected result..
foreach (var item in NewsModel.ToList())
{
if (NewsModel.Count() >= NewsModel.IndexOf(item) + 1)
{
_nextItem = NewsModel[NewsModel.IndexOf(item) + 1];
if (item.Name == _nextItem.Name)
{
NewsModel.Remove(item);
}
}
}
3
Answers
This will remove all adjacent entries that are equal.
EDIT
I missed that you want the ID’s to be updated by the end.
Do another for loop after the first one I sent, that does this
There are several methods. I wrote two methods(linq,iterator)
Linq
You can use Linq to create List without duplicates adjacent and can generate new Id with Index in Select
Result
iterator
use
Classes
Hum, the re-numbering of the ID is a bit of monkey wrench.
So, this:
Output:
Tough call if your requiring is to "in place" remove from existing list, or as the above does, and creates a new list.