Reputation: 349
I am having a list of list like below,
List<List<String>> ListsToMerge
Let's say this list is having 3 more inner list.
ListsToMerge [0] = {"Apple", "Grapes", "Banana"}
ListsToMerge [1] = {"Guava", "Apple", "Strawberry"}
ListsToMerge [2] = {"Strawberry", "Almonds", "Peach"}
I need to remove the duplicate entries from the above list and create a main list.
List<string> MergedList
This MergedList should remove the duplicate entries and only should contain
MergedList = {"Apple","Grapes","Banana","Guava","Strawberry","Almonds","Peach"}
Upvotes: 1
Views: 2032
Reputation: 37050
You can use some handy Linq extension methods to get the job done. SelectMany
will flatten the lists and select all the items, and Distinct
will remove any duplicates:
List<string> mergedLists = ListsToMerge.SelectMany(x => x).Distinct().ToList();
Upvotes: 1
Reputation: 3007
Try this: Without LINQ
List<string> MergedList = new List<string>();
foreach(List<string> ls in ListsToMerge)
{
foreach(string s in ls)
{
if(!MergedList.Contains(s))
{
MergedList.Add(s)
}
}
}
Upvotes: 3