StackUser
StackUser

Reputation: 349

How to remove duplicate entries from a list of list

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

Answers (2)

Rufus L
Rufus L

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

Precious Uwhubetine
Precious Uwhubetine

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

Related Questions