0

I have an array of json from the server. Like

ArrayExp = [
  {
    "id" : "number",
    "name" : "a name",
    ...
  }, 
  {
    "id" : "number",
    "name" : "a name",
    ...
  },
...
];

And I want to remove a "id" from all of the Array. I am trying with:

for (int i = 0; i < ArrayExp.Length; i++) {
    ArrayExp[i].id // I don't know how to remove it!
}

Can anyone help me?

5
  • Start by not mixing JS and C#. Commented Mar 16, 2018 at 11:43
  • ArrayExp.RemoveAt(i); If you are on c# Commented Mar 16, 2018 at 11:45
  • @HenkHolterman In c# you can do a loop like in js. The array is an example and I can do the ArrayExp[i].id to select the id from the object in c# . What do you mean? Commented Mar 16, 2018 at 11:47
  • @AamirNakhwa But I want to remove only the "id" in all object, not all of the object Commented Mar 16, 2018 at 11:50
  • I mean that [{"id" : "number", won't compile in C#. Post the actual class(es). Best to write a minimal reproducible example. Commented Mar 16, 2018 at 11:52

2 Answers 2

1

ArrayExp elements are objects of anonymous type.

In order to remove property on it, you should map each element into new one without id.

var newArrayExpr = 
          ArrayExp
              .Select(it => new { it.name, ... });
Sign up to request clarification or add additional context in comments.

1 Comment

it could be ok but I don't know if in the future the elements would change, I need do it without the name of elements... Only the "id" name
0

I used ExpandoObject from System.Dynamic, hope it helps you

public static void Main()
{
    var arrayExp = GetArray();
    var newCollection = ArrayExp.ToList().Select(x => RedefineObject(x, "Id"));
}

static object[] GetArray()
{
    var person1 = new { Name = "name", Id = 1 };
    var person2 = new { Name = "name", Id = 2 };
    var person3 = new { Name = "name", Id = 3 };
    return new[] { person1, person2, person3 };
}

static object RedefineObject(object obj, string propertyToRemove)
{
    var properties = obj.GetType().GetProperties().Where(x => x.Name != propertyToRemove);

    var dict = new Dictionary<string, object>();
    var eobj = new ExpandoObject();
    var eoColl = (ICollection<KeyValuePair<string, object>>)eobj;

    properties.ToList().ForEach(x => dict.Add(x.Name, x.GetValue(obj)));

    dynamic dynObj = dict;
    return dynObj;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.