Home > Software engineering >  Delete Value from list inside a list of objects
Delete Value from list inside a list of objects

Time:04-07

I Have this List of objects containing list of objects with tuple listProducts: (local variable) List<((string GroupName, string Valeurs)[] Levels, string[] Uids)> groupings

 [{
    "Item1": [{
        "Item1": "coloris",
        "Item2": "Beige"
    }, {
        "Item1": "ref_commercial",
        "Item2": "29245"
    }],
    "Item2": ["QB32-20220325-486274", "QB32-20220325-106045"]
}, {
    "Item1": [{
        "Item1": "coloris",
        "Item2": "Venezia"
    }, {
        "Item1": "ref_commercial",
        "Item2": "29245"
    }],
    "Item2": ["QB32-20220325-205994", "QB32-20220325-270903"]
}]

ListOfIds = ["QB32-20220325-486274", "QB32-20220325-106045", "QB32-20220325-205994", "QB32-20220325-270903"]

I want to loop through list of ids and check if exist on the listProducts, if so delete it from Item2.

So in the end Item2 will contains an empty list in this case.

CodePudding user response:

Loop over the main list then check if item2 list contain the id and delete it.

foreach(var id in ListOfIds)
    {
        foreach( var item in groupings)
        {
            if (item.Uids.Contains(id))
            {
                item.Uids.Remove(id);
            }
        }
    }

CodePudding user response:

Given that ValueTuple is a terrible way to store information that needs to be modified (create a class, or if you must, use an anonymous class) and given that C# Arrays should never be used for collections that must be modified (use a List<T>), here is some code to replace the elements in the List<T> that must be modified:

var listOfIds = new[] { "QB32-20220325-486274", "QB32-20220325-106045", "QB32-20220325-205994", "QB32-20220325-270903" }.ToHashSet();

for (int productIndex = 0; productIndex < listProducts.Count;   productIndex) {
    var product = listProducts[productIndex];
    product.Uids = product.Uids.Where(uid => !listOfIds.Contains(uid)).ToArray();
    listProducts[productIndex] = product;
}

CodePudding user response:

Use "classical loops" like for or foreach results in an error Cannot modify struct member when accessed struct is not classified as a variable. This happens because tuples are structs and when accessed inside a foreach or for you would be ending accessing a copy of this variable, not the variable itself.

But you can use LINQ to do that in a easy way

 listProducts = listProducts.Select(x =>
 {
     x.Uids = x.Uids.Except(ListOfIds).ToArray();
     return x;
 }).ToList();
  • Related