I have a list of generic objects. Each generic object has a specific field I need to remove.
I create the list like this.
list = new List<Object>();
list = JsonConvert.DeserializeObject<List<T>>(OutJson, new BooleanJsonConverter());
However i need to then remove a item from every object in that list. However i don't know how many or what objects are in the list. I do know that there will always be a field that i need to remove however.
I think I need to do something like this, but in a generic way.
//Loop through list objects, and for each object, loop through its
//properties. If any of the properties match a string, remove
//that property from the object.
foreach (var object in list)
{
foreach (var item in object)
{
if(item.ToUpper() == "SpecificKey")
{
list.Remove(item);
}
}
}
How do I loop through the generic object in a list and remove a specific item if it is present?
I think to complete this, it's better to mark the objects as dynamic.
Then this would work.
List<dynamic> list = JsonConvert.DeserializeObject<List<T>>(OutJson, new BooleanJsonConverter());
list.RemoveAll(x=>x["SpecificKey"]!=null);
I have a list of generic objects. Each generic object has a specific field I need to remove.
If you're trying to access a specific property on an objection, you can use reflection. See the answer here:
Get property value from string using reflection in C#
i need to then remove a item from every object in that list. However i don't know how many or what objects are in the list. I do know that there will always be a field that i need to remove however.
Your pseudocode is code is confusing, but it seems like you're just trying to remove a child from a parent object. If that is the case, and the child is a complex object, then set it equal to null
.
If you mean to say that you need to any object from the list that contains a property that has the specified property name, then you should know that you cannot remove items from a list while iterating through it using foreach
. See the answer here:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.