Home > Back-end >  Remove Objects items from a list that are in another other two lists
Remove Objects items from a list that are in another other two lists

Time:06-14

I'm new to C#, and I'm updating to mess with lists. I currently have this event Object. From it, I need to generate a new String list. I must remove all emails that are on Data3 and that are on Data1 and Data2.

{
  "event": 
    {
      "userData": [
        {
          "Data1": [
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "erick"
            },
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "isa"
            }
          ],
          "Data2": [
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "erick"
            }
          ],
          "Data3": [
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "erick"
            },
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "joseph"
            },
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "ju"
            },
            {
              "comentario": "",
              "email": "[email protected]",
              "name": "isa"
            }
          ]
        }
      ]
    }
}

The end result would be this:

Newlist = ["[email protected]", "[email protected]"]

As "[email protected]" and "[email protected]" are in Data1 and Data2, I should remove both from Data3, and return only the others.

CodePudding user response:

If you want to exclude elements from a list that are found in another list just use

var result= list1.Except(list2);

CodePudding user response:

You can use Enumerable.Except method as mentioned in previous answer. A complete example is given below:

List<String> list1 = new List<string>();
list1.Add("Apple");
list1.Add("Ball");
list1.Add("Car");

List<String> list2 = new List<string>();
list2.Add("Cat");
list2.Add("Dog");
list2.Add("Mouse");
list2.Add("Ball");

List<String> newList = list2.Except(list1).ToList();//don't forget to parse new list
  • Related