-2

I wanted to remove one item from existing object array and generate a separate object array without making the removed item as null in the new object array,

Array:

DataSet = new[]
                {
                    new DataSet
                    {
                        Item_1 = "value1",
                        Item_2 = "value2",

                    },
                    new DataSet
                    {
                        Item_1 = "value3",
                        Item_2 = "value4",

                    }
              }

Expected result:

"DataSet": [
    {
      "Item_1": "value3",
      "Item_2": "value4",

    }
  ]

Following code is working as expected:

var tempListDataSet = _response.DataSet.ToList();
    tempListDataSet.Remove(_response.DataSet[0]);
    response.DataSet = tempListDataSet.ToArray();

Just curious whether there is a better way of doing this?

SMPH
  • 2,369
  • 10
  • 45
  • 87

1 Answers1

1

If you want to skip the first one , you can use :

var result = _response.DataSet.Skip(1).ToArray();

Thought this will still create a new array and copy elements since arrays have a fixed size. Thread here is for your reference .

If you want to remove specific element , you could use linq :

var result = _response.DataSet.Where((source, index) => index != 1).ToArray();
Nan Yu
  • 23,741
  • 6
  • 55
  • 129